Search code examples
pythonjinja2

Split a string into a list in Jinja


I have some variables in a Jinja 2 template which are strings separated 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 is sometimes up to 10 strings inside the string, this gets messy.

I had a JSP part before where I did:

<% String[] list1 = val.get("variable1").split(";");%>
The grass is <%= list1[0] %> and the boat is <%= list1[1] %>

It works with:

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

Solution

  • 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 }}
    

    (This is after coming back to my own question after 5 years and seeing so many people found this useful, a little update.)