Scope of jinja template variables

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 sc_time with comma .. like 3.13,2.5,1.33, ...

So I entered var sep which I change internally if ... Reading ninja. I don't see anything about the scope inside loops or if and YES, I can actually use and change sep var ... in this example line

             {% set sep=',' %} 

      

and the next line

             [PROOF ... 

      

actually results in a mapping, BUT, next time

             {{- sep -}} 

      

just displays again as an empty var. What I am missing / don't understand here ...

+3


source to share


1 answer


The problem is the scope of the variable. The variable sep

within you for loops is considered a different variable than the variable you initialize at the top.



The same question and some answers are given here: Is it possible to expand the scope of a Jinja variable in an inner block?

+2


source







All Articles