【发布时间】:2014-09-03 20:44:51
【问题描述】:
使用这个 Flask 控制器的字典
projects = {
'life-calc':{'url':'life-calc',
'title': 'Life Calculator'},
'text-game':{'url':'text-game',
'title':'Text Adventure'},
'fill-it-up':{'url':'fill-it-up',
'title':'Fill It Up'},
'rock-paper-scissors':{'url':'rock-paper-scissors',
'title':'Rock, Paper, Scissors'},
'bubble-popper':{'url':'bubble-popper',
'title':'Bubble Popper'}
}
@app.route('/')
def index():
return render_template("index.html",
projects = projects)
以及模板本身
<h1>
List of My Projects
</h1>
<ol>
<li>
<a href = "life-calc">Life Calculator</a>
</li>
<li>
<a href = "text-game">Adventure Game</a>
</li>
<li>
<a href = "fill-it-up">Fill It Up</a>
</li>
<li>
<a href = "rock-paper-scissors">Rock Paper Scissors</a>
</li>
<li>
<a href = "bubble-popper">Bubble Popper</a>
</li>
</ol>
<p>test section below</p>
<ol>
{% for project in projects %}
<li><a href = "{{ project['url'] }}">{{ project['title'] }}</a> </li>
{% endfor %}
</ol>
{% endblock %}
如何访问 dict 中的项目以打印我的项目列表,如测试上方的 HTML 中一样?
我在Rendering a python dict in Jinja2 / Werkzeug 的帮助下解决了我自己的问题 模板块应该是
{% for key, value in projects.iteritems() %}
<li><a href={{value['url']}}>{{value['title']}}</a></li>
{% endfor %}
但我仍然很好奇如何访问更多嵌套字典,以及这是否是创建简单菜单的最聪明方法。
【问题讨论】:
标签: python dictionary flask jinja2