Mat*_*ttO 13 python dictionary jinja2 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)
Run Code Online (Sandbox Code Playgroud)
和模板本身
<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 %}
Run Code Online (Sandbox Code Playgroud)
如何访问dict中的项目以打印我的项目列表,如测试上方的HTML?
我在Jinja2/Werkzeug渲染一个python dict的帮助下解决了我自己的问题模板块 应该是
{% for key, value in projects.iteritems() %}
<li><a href={{value['url']}}>{{value['title']}}</a></li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
但我仍然很好奇如何访问更多嵌套字典,如果这是创建简单菜单的最明智的方法.
Nav*_*ava 21
我想你想知道如何访问模板中的嵌套字典
如果你认为我有你的问题
通常,这是访问字典中嵌套字典项的方法.
forloop深度级别,无论是列表还是字典.在这里,我只是以自己的方式给出一个通用的例子来帮助您理解
parent_dict = {1: {'A':'val1','B':'val2'}, 2:{'C':'val3','D':'val4'}}
Run Code Online (Sandbox Code Playgroud)
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)
小智 11
您也可以使用键来引用dict中的项目,而不是扩展循环中的键和值:
{% for project in projects %}
<li><a href = "{{ projects[project].url }}">{{ projects[project].title }}</a> </li>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25549 次 |
| 最近记录: |