Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate lists in JINJA2

Tags:

python

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?

like image 988
ccbunney Avatar asked Apr 08 '13 13:04

ccbunney


2 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 %}
like image 73
Jon Clements Avatar answered Sep 20 '22 09:09

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

like image 16
Jordan Stewart Avatar answered Sep 20 '22 09:09

Jordan Stewart