简体   繁体   中英

Jinja2 list is undefined

In Jinja2 I want to print the length of the 'first' value in a dictionary. In Python this would be done with the command len(list(my_dict.values())[0]) .

When I try this in Jinja2 I get the error 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

<!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. However, it provides a length method. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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