Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate int with str type in Jinja2 template?

I want to set a variable in jinja2 template which is a combination of string and a interger value.

Code is as follows:

{% set the_var = 'Wan_Links.WAN_' + i + '.wan_link_type' %}

Here "i" is a dynamic value and is of type int. When I run the above code I get the below error: TypeError: cannot concatenate 'str' and 'int' objects.

The expected output is the_var = Wan_Links.WAN_0.wan_link_type (i.e. i=0). Can anyone tell me how can I get this done?

like image 754
Abhijit Avatar asked Dec 28 '17 05:12

Abhijit


People also ask

How do I concatenate in Jinja?

You can use + if you know all the values are strings. Jinja also provides the ~ operator, which will ensure all values are converted to string first.

How do you write a for loop in Jinja2?

Jinja2 being a templating language has no need for wide choice of loop types so we only get for loop. For loops start with {% for my_item in my_collection %} and end with {% endfor %} . This is very similar to how you'd loop over an iterable in Python.


2 Answers

You can also use the ~ Operator:

~ Converts all operands into strings and concatenates them. {{ "Hello " ~ name ~ "!" }} would return (assuming name is set to 'John'): Hello John!.

http://jinja.pocoo.org/docs/2.10/templates/

like image 52
dmorlock Avatar answered Oct 03 '22 22:10

dmorlock


Got in done by adding "String" to it. Correct syntax is:

{% set the_var = 'Wan_Links.WAN_' + i|string + '.wan_link_type' %}
like image 40
Abhijit Avatar answered Oct 03 '22 20:10

Abhijit