I have some variables in a jinja2 template which are strings seperated by a ';'.
I need to use these strings separately in the code. i.e. the variable is variable1 = "green;blue"
{% list1 = {{ variable1 }}.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
I can split them up before rendering the template but since it are sometimes up to 10 strings inside the string this gets messy.
I had a jsp before where I did:
<% String[] list1 = val.get("variable1").split(";");%>
The grass is <%= list1[0] %> and the boat is <%= list1[1] %>
EDIT:
It works with:
{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}
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 %}
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.
Source: Stackoverflow.com