Search code examples
jinja2

Concatenate lists in JINJA2


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?


Solution

  • 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 %}