Python 在 JINJA2 中连接列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15879983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Concatenate lists in JINJA2
提问by ccbunney
How can I concatenate two list variables in jinja2?
如何在 jinja2 中连接两个列表变量?
E.G.
例如
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 %}
So, I have tried to concatenate the two lists using + (like you would in Python), but it turns out that they are not lists, but python xrangeobjects:
因此,我尝试使用 + 连接两个列表(就像在 Python 中一样),但事实证明它们不是列表,而是 Pythonxrange对象:
jijna2 error: unsupported operand type(s) for +: 'xrange' and 'xrange'
Is there a way for me to iterate over the concatenation of GRP1 and GRP2 in the same for loop?
有没有办法让我在同一个 for 循环中迭代 GRP1 和 GRP2 的串联?
采纳答案by Jon Clements
AFAIK you can't do it using native Jinja2 templating. You're better off creating a new combined iterable and passing that to your template, eg:
AFAIK 您不能使用本机 Jinja2 模板来做到这一点。您最好创建一个新的组合迭代并将其传递给您的模板,例如:
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
As per comments, you can explicitly convert the iterables into lists, and concatenate those:
根据评论,您可以将可迭代对象显式转换为列表,并将它们连接起来:
{% for M in GRP1|list + GRP2|list %}
回答by Jordan Stewart
Concatenating lists like {{ GRP1 + GRP2 }}is available, in at less jinja2 version v.2.9.5
类似的连接列表{{ GRP1 + GRP2 }}可用,在 jinja2 版本 v.2.9.5
@Hsiao gave this answer originally as a comment
@Hsiao 最初作为评论给出了这个答案

