jinja2 遍历元组列表

jinja2 iterate through list of tuples

我有一个名为 items:

的元组列表
[ (1,2), (3,4), (5,6), (7,8) ]

我以为我可以通过使用进行迭代,但它不起作用:

# Code
output = template.render( items )

# Template
{% for item in items %}
    {{ item[0] }};
    {{ item[1] }};
{% endfor %}

有什么建议吗?

来自documentation

render([context])

This method accepts the same arguments as the dict constructor: A dict, a dict subclass or some keyword arguments. If no arguments are given the context will be empty.

from jinja2 import Environment

TEMPLATE = """ 
{% for item in items %}
    {{ item[0] }};
    {{ item[1] }};
{% endfor %}
"""

template = Environment().from_string(TEMPLATE)

items = [(1,2), (3,4), (5,6), (7,8)]

print(template.render(items=items))

在解析模板时,jinja2 将寻找一个名为 'items' 的键,但在您的情况下,有 none,您必须明确指定它。