Jinja 的循环变量在 include-d 模板中不可用
我的 jinja 模板中有类似于以下的代码
{% for post in posts %}
{% include ["posts/" + post.type + ".html", "posts/default.html"] %}
{% endfor %}
,该模板应该根据 .type
渲染 posts
集合中的每个 post
> 的帖子。我为每个 post.type
设置了不同的模板。对于那些我没有模板的人,它会恢复为默认
帖子模板。
现在,我希望帖子的索引在帖子模板内从底部显示,该索引由 loop.revindex
提供。但由于某种原因,如果我在帖子模板中使用 loop.revindex
,我会收到一条错误消息 UndefinedError: 'loop' is undefined
。
那么,loop
在 include
d 模板中不可用吗?这是设计使然吗?我组织模板的方式是否有问题,导致该模板不可用?
编辑 好的,我想出了一个解决方法,在 for 循环中,在包含模板之前,我
{% set post_index = loop.revindex %}
在帖子模板中使用 post_index
。并不理想,但似乎是唯一的方法。但我仍然想知道你的解决方案。
编辑2另一件事,我可以访问include
d模板中的post
变量,但不能访问loop变量。
I have code similar to the following in one of my jinja template
{% for post in posts %}
{% include ["posts/" + post.type + ".html", "posts/default.html"] %}
{% endfor %}
which is supposed to render each post
inside the posts
collection, depending on the .type
of the post. I have a different template setup for each post.type
. And for those I don't have a template, it reverts to the default
post template.
Now, I want the index of the post being displayed from bottom, inside the post templates, which is provided by loop.revindex
. But for some reason, if I use loop.revindex
inside the post template, I get a error saying UndefinedError: 'loop' is undefined
.
So, is loop
not available in the include
d templates? Is this by design? Am I doing something wrong with how I organised my templates for this to be not available?
Edit Okay, I came up with a workaround, in the for loop, before I include my template, I do
{% set post_index = loop.revindex %}
and use post_index
inside the post template. Not ideal, but seems like the only way. I still want to know your solutions though.
Edit 2 One other thing, I am able to access the post
variable inside the include
d template, but not the loop
variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果可以使用
{% with %}
声明。尝试一下:
不要在包含的模板中使用
loop.revindex
,而是使用loop_revindex
。If might be possible with the
{% with %}
statement.Try this:
Instead of using
loop.revindex
in the included template, useloop_revindex
.另一种选择是通过将局部变量设置为
loop
,将整个loop
变量传递到包含的模板中,这使您可以访问所有
loop
s 属性,并且对我来说,在包含的模板中更清楚地了解变量是什么。Another option is to pass the entire
loop
variable into the included template by setting a local variable toloop
This gives you access to all of the
loop
s properties, and, to me, makes it more clear in the included template what the variable is.