jinja模板变量分配范围 [英] jinja template variable assignment scope

查看:54
本文介绍了jinja模板变量分配范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下Jinja代码段

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 %}

看看sep变量(分隔符的缩写),我想用逗号分隔sc_time.例如3.13,2.5,1.33,...

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

因此,我介绍了var sep,它在内部if中进行了更改.阅读忍者后,对于循环内的作用域或if和YES,我什么都没看到,我可以实际使用和更改sep var ...在此示例中线

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=',' %} 

已执行,并且下一行

             [PROOF ... 

实际上导致下次显示,但

actually results in displaying the , BUT, the next time

             {{- sep -}} 

再次将其呈现为空var.我在这里想念什么/不了解......

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

推荐答案

问题在于变量的作用域.您在循环中使用的sep变量被视为另一个变量,而不是您在顶部初始化的变量.

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.

此处提供了相同的问题和一些答案: 可以将Jinja变量的范围扩展到内部阻止吗?

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

这篇关于jinja模板变量分配范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆