Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string into list in jinja?

Tags:

python

jinja2

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] }} 
like image 435
user3605780 Avatar asked May 28 '15 19:05

user3605780


People also ask

How do you split a list in Jinja?

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.

How many delimiters are there in Jinja2?

there are two delimiters to split by here: first it's ",", and then the elements themselves are split by ":".

How do you split in Ansible?

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.


1 Answers

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 }} 
like image 67
user3605780 Avatar answered Sep 22 '22 00:09

user3605780