91
votes

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] }}
3
CAn you split the string before sending it to the template?kylieCatt
@IanAuld yes I can but like I said it gets messy because it are a lot of strings and they all contain a lot of strings inside them.user3605780
You could write your own filter to do a split on whatever character you like. See stackoverflow.com/questions/20678004/…junnytony

3 Answers

150
votes

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 }}
20
votes

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 %}
12
votes

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.