templates - Jinja 变量的范围可以超出内部 block 吗?

标签 templates variables scope jinja2

我有以下 Jinja 模板:

{% set mybool = False %}
{% for thing in things %}
    <div class='indent1'>
        <ul>
            {% if current_user %}
              {% if current_user.username == thing['created_by']['username'] %}
                {% set mybool = True %}
                <li>mybool: {{ mybool }}</li> <!-- prints True -->
                <li><a href='#'>Edit</a></li>
              {% endif %}
            {% endif %}
            <li>Flag</li>
        </ul>
    </div>
    <hr />
{% endfor %}

{% if not mybool %}
    <!-- always prints this -->
    <p>mybool is false!</p>
{% else %}
  <p>mybool is true!</p>
{% endif %}

如果 for 循环中满足条件,我想将 mybool 更改为 true,以便可以显示 mybool is true! 下面。但是,内部 mybool 的范围似乎仅限于 if 语句,因此期望的 mybool从未设置。

如何设置“全局”mybool 以便我可以在最后一个 if 语句中使用它?

编辑

我找到了some suggestions (只有正确缓存的页面 View ),但它们似乎不起作用。也许它们在 Jinja2 中已被弃用...

编辑

下面提供了解决方案。我仍然很好奇为什么上面的建议不起作用。有谁确切知道它们已被弃用?

最佳答案

解决此限制的一种方法是启用 "do" expression-statement extension并使用数组而不是 bool 值:

{% set exists = [] %}
{% for i in range(5) %}
      {% if True %}
          {% do exists.append(1) %}
      {% endif %}
{% endfor %}
{% if exists %}
    <!-- exists is true -->
{% endif %}

要启用 Jinja 的“do”表达式语句扩展:e = jinja2.Environment(extensions=["jinja2.ext.do",])

关于templates - Jinja 变量的范围可以超出内部 block 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4870346/

相关文章:

javascript - 全局变量和 JavaScript 中的 'window.variable' 有什么区别?

templates - Golang 模板(并将函数传递给模板)

c++ - 我对 enable_if 和 has_member 做错了什么?

c# - C# 中可能的意外引用比较

swift - for循环变量名使用swift

c - 链表: C: does not store the values I am looking for

c++ - JIT 编译能比编译时模板实例化运行得更快吗?

c++ - 不明确的模板实例化

javascript - 停止间隔有问题 [JS]

python - 无参数输入的函数可变范围