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] }}
Call "{% set split_list = str. split(delim) %}" in a format string to assign split_list to a list where each element is split by delim in str . Use {{ split_list }} in the format string, where split_list is the previous result to output the result of split_list . Call jinja2.
there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".
Split Lines in Ansible You can use the 'split()' function to divide a line into smaller parts. The output will be a list or dictionary. This is a Python function and not a Jinja2 filter. For example, in the below example, I am splitting the variable 'split_value' whenever a space character is seen.
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With