Merge multiple lists in Jinja2

Viewed 2766

Is there a way to combine multiple lists in a list in Jinja2 ?

For instance, if I have :

[['foo', 'moo'],['py','jinga','template'],['example'],['stack','overflow']]

I expect to get :

['foo', 'moo','py','jinga','template','example','stack','overflow']

(I don't know the number of lists in the list in advance.)

I already tried to use join() but it doesn't work because I get a string and not a list of strings.

1 Answers

If you don't know upfront the number of sub list, since Jinja won't allow assignment in loops, what you could do is to join back the sub lists via map, then, split it back.

It is not the perfect way, but it does the job.

{{ ([['foo', 'moo'],['py','jinga','template'],['example'],['stack','overflow']] | map('join','|||') | join('|||')).split('|||') }}

You can do a concatenation of lists using the + operator:

['foo','moo'] + ['py','jinga','template'] + ['example'] + ['stack','overflow']

Gives

['foo', 'moo', 'py', 'jinga', 'template', 'example', 'stack', 'overflow']

+ Adds two objects together. Usually the objects are numbers, but if both are strings or lists, you can concatenate them this way.

Source: https://jinja.palletsprojects.com/en/2.11.x/templates/#math

Related