jinja template variable assignment scope

人走茶凉 提交于 2019-12-10 18:43:12

问题


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....


回答1:


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?



来源:https://stackoverflow.com/questions/14726396/jinja-template-variable-assignment-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!