Append to string

In Jinja2, the scope of a variable defined within a for-loop is limited to the for-loop. A variable defined outside a for-loop can be modified within a for-loop but that value isn’t preserved outside of the for-loop. To get the variable’s scope to cover inside and outside the for-loop, use namespace.

{% set ns = namespace(c = '') %}
{% for i in range(0,3) %}
 {% set ns.c = ns.c ~ '5' %}
{% endfor %}
{{ ns.c }}

In addition, is you use the + operator it will naturally attempt to compute the sum of numbers. If you want to append numeric strings, and eliminate any ambiguity of whether the values should be summed or concatenated, use the ~ operator.

2 Likes