Jinja2 中多个同名块
在 Jinja2 中,我有一个如下所示的基本模板:
<title>{% block title %}{% endblock %} - example.com</title>
[...]
<h1>
{% block title %}{% endblock %} - example.com
</h1>
Jinja2 然后失败并显示以下消息:
lines = [self.message, ' ' + location]
: block 'title' defined twice
它必须是现在很明显我想要做什么 - 在两个地方具有相同的标题:TITLE 标签和 H1 标签,但标题的部分实际上是由其他派生模板提供的。
通常如何实现这一目标?
In Jinja2, I have a base template like this:
<title>{% block title %}{% endblock %} - example.com</title>
[...]
<h1>
{% block title %}{% endblock %} - example.com
</h1>
Jinja2, then, fails with the following message:
lines = [self.message, ' ' + location]
: block 'title' defined twice
It must be now evident as to what I am trying to do - to have the same title in two places: the TITLE tag and the H1 tag, but the part of the title is actually provided by other derived templates.
How does one typically achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如此处所述,定义块会创建一个宏,其名称为块在特殊的“self”对象中:
As documented here, defining a block creates a macro with the name of the block in the special "self" object:
这个想法是在宏内创建一个块,然后调用宏两次,而不是让“块”标签重复两次。
在最新的 Jinja2 版本中,此功能有效:
layout.html
child_page.html
The idea is to create a block inside a macro and then call macro two times, instead of having "block" tag repeated twice.
In latest Jinja2 version this works:
layout.html
child_page.html