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?
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.
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.
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/
Got in done by adding "String" to it. Correct syntax is:
{% set the_var = 'Wan_Links.WAN_' + i|string + '.wan_link_type' %}
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