Concatenate lists in JINJA2

Question:

How can I concatenate two list variables in 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 xrange objects:

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?

Asked By: ccbunney

||

Answers:

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:

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 %}
Answered By: Jon Clements

Concatenating lists like {{ GRP1 + GRP2 }} is available, in jinja2 versions 2.9.5 and above.

@Hsiao gave this answer originally as a comment

Answered By: Jordan Stewart
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.