简体   繁体   English

Jinja2中有多个同名的块

[英]Multiple blocks of same name in Jinja2

In Jinja2 , I have a base template like this: Jinja2中 ,我有一个这样的基本模板:

<title>{% block title %}{% endblock %} - example.com</title>
[...]

<h1> 
  {% block title %}{% endblock %} - example.com
</h1>

Jinja2, then, fails with the following message: 然后,Jinja2失败并显示以下消息:

  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. 现在必须明确我要做的事情 - 在两个地方拥有相同的标题:TITLE标签和H1标签,但标题的一部分实际上是由其他派生模板提供的。

How does one typically achieve this? 人们通常如何实现这一目标?

As documented here , defining a block creates a macro with the name of the block in the special "self" object: 如此处所述 ,定义块会在特殊的“self”对象中创建一个带有块名称的宏:

<title>{% block title %}{% endblock %} - example.com</title>
[...]

<h1> 
  {{ self.title() }} - example.com
</h1>

The idea is to create a block inside a macro and then call macro two times, instead of having "block" tag repeated twice. 想法是在宏内部创建一个块,然后调用宏两次,而不是重复两次“block”标记。

In latest Jinja2 version this works: 在最新的Jinja2版本中,这有效:

layout.html 的layout.html

{%- extends "base.html" -%}

{%- macro duplicated() -%}
    {% block overrideninchild %}{% endblock %}
{%- endmacro -%}

{% block base_content %}
    {{ duplicated() }}
    {{ duplicated() }}
{% endblock %}

child_page.html child_page.html

{%- extends "layout.html" -%}

{% block overrideninchild %}
   Should be visible twice.
{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM