问题
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