连接JINJA2中的列表

ccb*_*ney 17 python jinja2

如何在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)

  • @KernowBunney在这种情况下,要么是2个循环 - 或者看看`{GRP1中的M是%|列表+ GRP2 |列表%}`有效吗? (7认同)
  • 这在Ansible中非常有用,同时为AWS VPC构建路由.我将每个路由作为一个单独的数组事实,然后将它们全部连接成一个数组,其中包含`vpc_routes:"{{vpc_main_routes + optional_route1 | default([])+ optional_route2 | default([])}}"`.注意可选的路由之一可能是未定义的. (4认同)

Jor*_*art 11

{{ GRP1 + GRP2 }}在 jinja2 版本 2.9.5 及更高版本中,可以使用连接列表。

@Hsiao 最初作为评论给出了这个答案