我在Jinja2中进行代码生成,我经常想要一起遍历两个列表(即变量名称和类型),是否有一种简单的方法可以执行此操作,还是只需要传递一个预压缩列表?我无法在docs或谷歌搜索中找到这样的功能。
答案 0 :(得分:36)
如果您认为合适,请修改jinja2.Environment global namespace本身。
import jinja2
env = jinja2.Environment()
env.globals.update(zip=zip)
# use env to load template(s)
这可能有助于将视图(模板)逻辑与应用程序逻辑分离,但它也可以反转。 #separationofconcerns
答案 1 :(得分:6)
由于您没有提及您是否使用Flask,我认为我添加了我的发现。
要render_template()
使用,请创建' zip'使用Flask使用的Jinja2环境中的zip()
函数进行过滤。
app = Flask(__name__)
...
app.jinja_env.filters['zip'] = zip
要在模板中使用它,请执行以下操作:
{% for value1, value2 in iterable1|zip(iterable2) %}
{{ value1 }} is paired with {{ value2 }}
{% endfor %}
请记住,字符串是可迭代的Jinja2,所以如果你试图压缩字符串,你会得到一些疯狂的东西。要确保您想要压缩的内容是可迭代的而不是字符串,请执行以下操作:
{% if iterable1 is iterable and iterable1 is not string
and iterable2 is iterable and iterable2 is not string %}
{% for value1, value2 in iterable1|zip(iterable2) %}
{{ value1 }} is paired with {{ value2 }}
{% endfor %}
{% else %}
{{ iterable1 }} is paired with {{ iterable2 }}
{% endif %}
答案 2 :(得分:3)
我不认为模板语言允许在for循环中执行两个容器的zip。以下是django的类似问题,而jinja模板与django非常接近。
您可以预先建立压缩容器并传递给模板。
>> for i,j in zip(range(10),range(20,30)):
... print i,j
...
相当于
>>> [(i,j) for i,j in zip(range(10),range(20,30))]
答案 3 :(得分:0)
对于Flask,您可以在render_template()
return render_template("home.html", zip=zip)