Jinja2具有块和包含的继承 [英] Jinja2 Inheritance with Blocks and Includes
问题描述
我不知道如何使用Jinja2从包含的模板中修改块.这是我使用三个文件的示例.
I can't figure out how to modify blocks from included templates using Jinja2. Here's an example where I use three files.
base.html:
base.html:
<html>{% include "content.html" %}</html>
content.html:
content.html:
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>
story.html
story.html
{% extends "base.html" %}
{% block title %}story.title{% endblock title %}
{% block content_body %}story.description{% endblock content_body %}
渲染story.html时,我会得到:
When rendering story.html, I'll get:
<html>
<h1>Title</h1>
<div>Content Body</div>
</html>
如何渲染期望值?
推荐答案
base.html
未呈现,因为任何模板均未调用它.您可以可以做的是第二级扩展:
base.html
is not rendered because it's not invoked by any template. What you could do is a second level of extension:
base.html:
base.html:
<html>{% block html %}{% endblock %}</html>
content.html:
content.html:
{% extends "base.html" %}
{% block html %}
<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>
{% endblock %}
尽管如此,这可能有些过头,您可能会发现一个基本模板就足够了(即将base.html
和content.html
组合成一个模板).
Still, that is probably overkill, you will likely find that a single base template is enough (i.e. combine base.html
and content.html
into a single template).
这篇关于Jinja2具有块和包含的继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!