如何在jinja2中连接两个列表变量?
例如
GRP1 = [1, 2, 3]
GRP2 = [4, 5, 6]
{# This works fine: #}
{% for M in GRP1 %}
Value is {{M}}
{% endfor %}
{# But this does not: #}
{% for M in GRP1 + GRP2 %}
Value is {{M}}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
所以,我试图使用+连接两个列表(就像在Python中一样),但事实证明它们不是列表,而是python xrange对象:
jijna2 error: unsupported operand type(s) for +: 'xrange' and 'xrange'
Run Code Online (Sandbox Code Playgroud)
有没有办法让我在同一个for循环中迭代GRP1和GRP2的串联?
Jon*_*nts 18
使用原生Jinja2模板你无法做到AFAIK.您最好创建一个新的组合迭代并将其传递给您的模板,例如:
from itertools import chain
x = xrange(3)
y = xrange(3, 7)
z = chain(x, y) # pass this to your template
for i in z:
print i
Run Code Online (Sandbox Code Playgroud)
根据评论,您可以显式地将迭代转换为列表,并连接这些:
{% for M in GRP1|list + GRP2|list %}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21330 次 |
| 最近记录: |