![](/img/trans.png)
[英]How to get a Python dict into an HTML template using Flask/Jinja2
[英]Get nested dict items using Jinja2 in Flask
这个带有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 %}
我如何访问字典中的项目以打印测试上方的HTML中的项目列表?
我在Jinja2 / Werkzeug中渲染python dict的帮助下解决了自己的问题, 模板块应为
{% for key, value in projects.iteritems() %}
<li><a href={{value['url']}}>{{value['title']}}</a></li>
{% endfor %}
但是我仍然对如何访问更多的嵌套字典感到好奇,并且这是否是创建简单菜单的最明智的方法。
我想您想知道如何访问模板中的嵌套字典
如果你认为我有你的问题
通常,这是访问字典中嵌套的字典项的方法。
forloop
深度级别。 在这里,我以自己的方式举一个通用的例子,供您理解
parent_dict = {1: {'A':'val1','B':'val2'}, 2:{'C':'val3','D':'val4'}}
{% for key,parent_dict_item in parent_dict.items() %}
{% for key2, nested_value in parent_dict_item.items() %}
<li><a href = "{{ nested_value }}">{{ nested_value }}</a> </li>
{% endfor %}
{% endfor %}
<li><a href="val1">val1</a> </li>
<li><a href="val2">val2</a> </li>
<li><a href="val3">val3</a> </li>
<li><a href="val4">val4</a> </li>
除了在循环中扩展键和值之外,还可以使用键在dict本身中引用项目:
{% for project in projects %}
<li><a href = "{{ projects[project].url }}">{{ projects[project].title }}</a> </li>
{% endfor %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.