Jinja 变量的范围可以扩展到内部块之外吗? [英] Can a Jinja variable's scope extend beyond in an inner block?

查看:36
本文介绍了Jinja 变量的范围可以扩展到内部块之外吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Jinja 模板:

{% set mybool = False %}{% 事物中的事物 %}

<ul>{% if current_user %}{% if current_user.username == thing['created_by']['username'] %}{% set mybool = True %}<li>mybool: {{ mybool }}</li><!-- 打印 True --><li><a href='#'>编辑</a></li>{% 万一 %}{% 万一 %}<li>标志</li>

<小时/>{% 结束为 %}{% 如果不是 mybool %}<!-- 总是打印这个 --><p>mybool 是假的!</p>{% 别的 %}<p>mybool 是真的!</p>{% 万一 %}

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

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

编辑

我找到了 一些建议(仅正确缓存页面视图),但它们似乎不起作用.也许它们在 Jinja2 中已被弃用...

编辑

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

解决方案

解决此限制的一种方法是启用 "do" 表达式语句扩展 并使用数组而不是布尔值:

{% set exists = [] %}{% for i in range(5) %}{% 如果是真的 %}{% 确实存在.追加(1)%}{% 万一 %}{% 结束为 %}{% 如果存在 %}<!-- 存在为真-->{% 万一 %}

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

I have the following Jinja template:

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

If the condition is met in the for loop, I'd like to change mybool to true so I can display mybool is true! below. However, it looks like the scope of the inner mybool is limited to the if statement, so the desired mybool is never set.

How can I set the "global" mybool so I can use it in the last if statement?

EDIT

I've found some suggestions (only the cached page views correctly), but they don't seem to work. Perhaps they're deprecated in Jinja2...

EDIT

Solution provided below. I am still curious why the suggestions above do not work though. Does anyone know for sure that they were deprecated?

解决方案

One way around this limitation is to enable the "do" expression-statement extension and use an array instead of boolean:

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

To enable Jinja's "do" expression-statement extension: e = jinja2.Environment(extensions=["jinja2.ext.do",])

这篇关于Jinja 变量的范围可以扩展到内部块之外吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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