Abhijit
Abhijit

Reputation: 1856

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?

Upvotes: 23

Views: 29072

Answers (2)

dmorlock
dmorlock

Reputation: 2021

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/

Upvotes: 34

Abhijit
Abhijit

Reputation: 1856

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

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

Upvotes: 23

Related Questions