如何将选定的命名参数传递给 Jinja2 的包含上下文?
使用 Django 模板引擎,我可以在使用命名参数设置自定义上下文时包含另一个部分模板,如下所示:
{% include "list.html" with articles=articles_list1 only %}
{% include "list.html" with articles=articles_list2 only %}
正如您可能假设的,articles_list1
和 articles_list2
是两个不同的列表,但我可以重用相同的 list.html
模板,该模板将使用 articles
变量。
我正在尝试使用 Jinja2 实现相同的目标,但我看不到推荐的方法,因为不支持 with
关键字。
Using Django templating engine I can include another partial template while setting a custom context using named arguments, like this:
{% include "list.html" with articles=articles_list1 only %}
{% include "list.html" with articles=articles_list2 only %}
As you may be supposing, articles_list1
and articles_list2
are two different lists, but I can reuse the very same list.html
template which will be using the articles
variable.
I'm trying to achieve the same thing using Jinja2, but I can't see what's the recommended way, as the with
keyword is not supported.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Jinja2 有
with
关键字 - 它不会'它不会为您提供与 Django 相同的语法,它可能不会按照您预期的方式工作,但您可以这样做:但是,如果
list.html
基本上只是作为创建列表的一种方式,那么您可能想将其更改为宏
相反 - 这将为您提供更大的灵活性。要从另一个模板使用此宏,请导入它:
Jinja2 has the
with
keyword - it won't give you the same syntax as Django, and it may not work the way you anticipate but you could do this:However, if
list.html
is basically just functioning as a way to create a list then you might want to change it to amacro
instead - this will give you much more flexibility.To use this macro from another template, import it:
这样你就可以将多个变量传递给Jinja2 Include语句 - (通过在With语句中用逗号分隔变量):
This way you can pass multiple variables to Jinja2 Include statement - (by splitting variables by comma inside With statement):
对于 2017 年以上的读者,自
2.9
开始,Jinja 默认包含with
语句。无需延期。http://jinja.pocoo.org/docs/2.9/templates/#with -声明
For readers in 2017+, Jinja as of
2.9
includes thewith
statement by default. No extension necessary.http://jinja.pocoo.org/docs/2.9/templates/#with-statement
更新2021+
默认情况下,包含的模板可以访问活动上下文的变量
。有关导入和包含的上下文行为的更多详细信息,请参阅导入上下文行为< /a>.从 Jinja 2.2 开始,您可以使用
忽略缺失
来标记包含;在这种情况下,如果要包含的模板不存在,Jinja 将忽略该语句。当与with
或without context
结合使用时,它必须放置在上下文可见性语句之前。以下是一些有效的示例:Updated 2021+
Included templates have access to the variables of the active context by default
. For more details about context behavior of imports and includes, see Import Context Behavior.From Jinja 2.2 onwards, you can mark an include with
ignore missing
; in which case Jinja will ignore the statement if the template to be included does not exist. When combined withwith
orwithout context
, it must be placed before the context visibility statement. Here are some valid examples:另一种无需插件的选择是使用宏并将其包含在另一个文件中:
文件 macro.j2
文件 main.j2< /em>
Another option, without plugins, is to use macros and include them from another file:
file macro.j2
file main.j2