Jinja2:在循环内更改变量的值 [英] Jinja2: Change the value of a variable inside a loop

查看:109
本文介绍了Jinja2:在循环内更改变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在循环内更改在循环外声明的变量的值.但是总是在变化,它将初始值保持在循环之外.

I want to change the value of the variable declared outside the loop within a loop. But always changing, it keeps the initial value outside the loop.

{% set foo = False %}

{% for item in items %}
  {% set foo = True %}
  {% if foo %} Ok(1)! {% endif %}
{% endfor %}

{% if foo %} Ok(2)! {% endif %}

这将呈现:

Ok(1)!

因此,到目前为止发现的唯一(坏)解决方案是:

So the only (bad) solution have found so far was this:

{% set foo = [] %}

{% for item in items %}
  {% if foo.append(True) %} {% endif %}
  {% if foo %} Ok(1)! {% endif %}
{% endfor %}

{% if foo %} Ok(2)! {% endif %}

这将呈现:

Ok(1)!
Ok(2)!

但是,它非常丑陋!还有另一个更优雅的解决方案吗?

But, its is very ugly! Is there another more elegant solution?

推荐答案

也尝试基于字典的方法.似乎不太丑.

Try also dictionary-based approach. It seems to be less ugly.

{% set vars = {'foo': False} %}

{% for item in items %}
  {% if vars.update({'foo': True}) %} {% endif %}
  {% if vars.foo %} Ok(1)! {% endif %}
{% endfor %}

{% if vars.foo %} Ok(2)! {% endif %}

这也会呈现:

Ok(1)!
Ok(2)!

这篇关于Jinja2:在循环内更改变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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