Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jinja template variable assignment scope

Given the following Jinja snippet

        {% set sep='' %}                
        {% for stamp in stamp_list -%}
            {%- for heartbeat in heartbeat_list -%}
                {%- if heartbeat.name == site.name and heartbeat.stamp == stamp.stamp -%}
                    {{- heartbeat.sc_time -}}
                    {{- sep -}}
                    {% set sep=',' %}
                                            [PROOF for new value {{ sep }}]
                {%- endif -%}
            {%- endfor -%}
        {%- endfor %}

Look at the sep variable (short for separator) I want to separate the sc_time with comma's.. like 3.13,2.5,1.33,...

So I introduce the var sep, which I change in the inner if.. Reading the Ninja I see nothing about scope inside for loops or if's and YES I can actually use and change the sep var... in this sample the line

             {% set sep=',' %} 

is executed and the following line

             [PROOF ... 

actually results in displaying the , BUT, the next time

             {{- sep -}} 

just renders again as an empty var. What am I missing / not understanding here....

like image 840
Paul Avatar asked Apr 28 '26 23:04

Paul


1 Answers

The problem is the scope if the variable. The sep variable inside you for loops is considered to be another variable than the variable you initialize at the top.

The same question and some answers are provided here: Can a Jinja variable's scope extend beyond in an inner block?

like image 121
gecco Avatar answered May 01 '26 13:05

gecco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!