Python Flask 模板 - For 循环迭代 key:value
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45167508/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Flask Template - For Loop Iteration key:value
提问by Johnny John Boy
I've got an HTML template with a Flask Jinja for loop in it which generates a table and looks like:
我有一个带有 Flask Jinja for 循环的 HTML 模板,它生成一个表格,如下所示:
<tbody>
{% for segment in segment_details %}
<tr>
<td>{{segment}}</td>
<td>{{segment_details['{{segment}}']}}</td>
</tr>
{% endfor %}
</tbody>
I'm trying to iterate through a document of varying length/keys and present each row in the table as the key and value. In my Python code I've got this which has the desired response in the shell:
我正在尝试遍历不同长度/键的文档,并将表中的每一行显示为键和值。在我的 Python 代码中,我得到了它在 shell 中具有所需的响应:
for item in segment_details:
print(item, segment_details[item])
But in Flask I get the item correctly listing all the rows but the
但是在 Flask 中,我得到了正确列出所有行的项目,但
{{segment_details['{{segment}}']}}
{{segment_details['{{segment}}']}}
Isn't producing any values, I've tried with and without the single quotes. Is this possible?
不产生任何值,我试过使用和不使用单引号。这可能吗?
采纳答案by kemis
This is where your error is:
这是您的错误所在:
<td>{{segment_details['{{segment}}']}}</td>
There is no need for the {{ }}
inside.
It should be just:
{{ }}
内部不需要。它应该只是:
<td>{{segment_details[segment]}}</td>
For more see the documentation for Jinja.
When you are writing a statement(if
, for
) in Jinja2
you use {% statement %}
but when you are accessing a variable then just use {{ variable }}
.
有关更多信息,请参阅Jinja的文档。当你写一个声明(if
,for
中)Jinja2
你使用{% statement %}
,但是当你访问一个变量就用{{ variable }}
。
回答by Luis Carlos Herrera Santos
it is a solution
这是一个解决方案
<tbody>
{% for key, segment in segment_details.items() %}
<tr>
<td>{{ key }}</td>
<td>{{ segment }}</td>
</tr>
{% endfor %}
</tbody>