【问题标题】:Jinja's loop variable is not available in include-d templatesJinja 的循环变量在 include-d 模板中不可用
【发布时间】:2012-01-11 12:00:35
【问题描述】:

我的一个 jinja 模板中有类似于以下的代码

{% for post in posts %}
    {% include ["posts/" + post.type + ".html", "posts/default.html"] %}
{% endfor %}

应该在posts 集合中呈现每个post,具体取决于帖子的.type。我为每个post.type 设置了不同的模板。对于那些我没有模板的人,它会恢复为default 帖子模板。

现在,我希望在loop.revindex 提供的帖子模板内从底部显示帖子的索引。但由于某种原因,如果我在帖子模板中使用loop.revindex,则会收到错误消息UndefinedError: 'loop' is undefined

那么,loopincluded 模板中不可用吗?这是设计使然吗?我在组织模板的方式上是否做错了,导致该模板不可用?

编辑好的,我想出了一个解决方法,在 for 循环中,在我包含我的模板之前,我会这样做

{% set post_index = loop.revindex %}

并在帖子模板中使用post_index。不理想,但似乎是唯一的方法。不过我还是想知道你的解决方案。

编辑 2 另一件事,我可以访问 included 模板中的 post 变量,但不能访问 loop 变量。

【问题讨论】:

    标签: python jinja2 template-inheritance


    【解决方案1】:

    如果有可能使用{% with %} 语句。

    试试这个:

    {% with %}
        {% set loop_revindex = loop.revindex %}
        {% include ... %}
    {% endwith %}
    

    不要在包含的模板中使用loop.revindex,而是使用loop_revindex

    【讨论】:

    • 是的,将其设置为另一个局部变量是解决方案,我在发布问题后立即想到。请参阅我对问题的编辑。不过不需要with。也不知道with,谢谢你的提示:)
    【解决方案2】:

    另一种选择是将整个 loop 变量传递到包含的模板中,方法是将局部变量设置为 loop

    {% for post in posts %}
        {% set post_loop = loop %}
        {% include ["posts/" + post.type + ".html", "posts/default.html"] %}
    {% endfor %}
    

    这使您可以访问所有loops 属性,并且对我来说,在包含的模板中更清楚地知道变量是什么。

    【讨论】:

      猜你喜欢
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多