Split string into list in jinja?
If there are up to 10 strings then you should use a list in order to iterate through all values.
{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}
After coming back to my own question after 5 year and seeing so many people found this useful, a little update.
A string variable can be split into a list
by using the split function (it can contain similar values, set
is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
or
{% set list1 = variable1.split(';') %}
{% for item in list1 %}
<p>{{ item }}<p/>
{% endfor %}
or
{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}
You can’t run arbitrary Python code in jinja; it doesn’t work like JSP in that regard (it just looks similar). All the things in jinja are custom syntax.
For your purpose, it would make most sense to define a custom filter, so you could for example do the following:
The grass is {{ variable1 | splitpart(0, ',') }} and the boat is {{ splitpart(1, ',') }}
Or just:
The grass is {{ variable1 | splitpart(0) }} and the boat is {{ splitpart(1) }}
The filter function could then look like this:
def splitpart (value, index, char = ','):
return value.split(char)[index]
An alternative, which might make even more sense, would be to split it in the controller and pass the splitted list to the view.