简体   繁体   English

Jinja2列表未定义

[英]Jinja2 list is undefined

In Jinja2 I want to print the length of the 'first' value in a dictionary. 在Jinja2中,我想在字典中打印“ first”值的长度。 In Python this would be done with the command len(list(my_dict.values())[0]) . 在Python中,这可以通过命令len(list(my_dict.values())[0])

When I try this in Jinja2 I get the error jinja2.exceptions.UndefinedError: 'list' is undefined . 当我在Jinja2中尝试此操作时,出现错误jinja2.exceptions.UndefinedError: 'list' is undefined

Minimum working example: 最低工作示例:

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")

with in template.html the code 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>

How do I solve this? 我该如何解决?

You cannot use Python list in jinja2 template because it's not Python, it is a mark language. 您不能在jinja2模板中使用Python list ,因为它不是Python,而是标记语言。 However, it provides a length method. 但是,它提供了一个length方法。 Instead of: 代替:

{% if len(dict.values()[0]) > 1 %}

You should write: 您应该写:

{% if dict.values()[0] | length > 1 %}

# or
{% if dict.values() | first | length > 1 %}

Please see doc for more examples. 请参阅文档以获取更多示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM