简体   繁体   English

如何在jinja2模板中重复一个块?

[英]How to repeat a block in a jinja2 template?

I'm using Jinja2 as the template engine to a static HTML site generated through a Python script. 我正在使用Jinja2作为通过Python脚本生成的静态HTML网站的模板引擎。

I want to repeat the content of a block in the layout template, which goes something like this: 我想在布局模板中重复一个块的内容,如下所示:

<html>
<head>
    <title>{% block title %}{% endblock %} - {{ sitename }}</title>
</head>
<body>
    <h1>{% block title %}{% endblock %}</h1>
    <div id="content">
        {% block content %}{% endblock %}
    </div>
</body>
</html>

This template will be extended in a page template, that looks like this: 此模板将在页面模板中进行扩展,如下所示:

{% extends "layout.html" %}
{% block title %}Page title{% endblock %}
{% block content %}
Here goes the content
{% endblock %}

However, this doesn't work as I expected, resulting in an error: 但是,这不能像我预期的那样工作,导致错误:

jinja2.exceptions.TemplateAssertionError: block 'title' defined twice

Jinja interprets the second {% block title %} in layout.html as a block redefinition. Jinja将layout.html中的第二个{% block title %}解释为块重新定义。

How can I repeat the content of a block in the same template using jinja2? 如何使用jinja2在同一模板中重复块的内容?

Use the special self variable to access the block by name: 使用特殊self变量按名称访问块:

<title>{% block title %}{% endblock %} - {{ sitename }}</title>
<!-- ... snip ... -->
<h1>{{ self.title() }}</h1>

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

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