[英]Jinja2 list is undefined
在Jinja2中,我想在字典中打印“ first”值的長度。 在Python中,這可以通過命令len(list(my_dict.values())[0])
。
當我在Jinja2中嘗試此操作時,出現錯誤jinja2.exceptions.UndefinedError: 'list' is undefined
。
最低工作示例:
from jinja2 import Template, DebugUndefined
from shutil import copyfile
def main(file_name_template, file_name_log):
# Copy template file 'file_name_template' to 'file_name_log' so that logging can start.
copyfile(file_name_template, file_name_log)
template = Template(open(file_name_log).read(), undefined=DebugUndefined)
# Define test variable 'my_dict'.
my_dict = {'key_0': 4641896,
'key_1': 189478415,
'key_2': 841653}
# Start logging.
template_render_dict = {'my_dict': my_dict}
# Save log to external file and possibly open upon completion of the 'main' program.
template_rendered = template.render(template_render_dict) # Render the template to the filled in log report.
if __name__ == "__main__":
main("template.html", "template_rendered.html")
在template.html
包含代碼
<!DOCTYPE html>
<html lang="en">
<body>
{{my_dict}}<br/>
{{my_dict.keys()}}<br/>
{{my_dict.values()}}<br/>
{{len(list(my_dict.values())[0])}}<br/>
</body>
</html>
我該如何解決?
您不能在jinja2模板中使用Python list
,因為它不是Python,而是標記語言。 但是,它提供了一個length
方法。 代替:
{% if len(dict.values()[0]) > 1 %}
您應該寫:
{% if dict.values()[0] | length > 1 %}
# or
{% if dict.values() | first | length > 1 %}
請參閱文檔以獲取更多示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.