Jinja2 Inheritance with Blocks and Includes

2019-03-14 16:54发布

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:

<html>{% include "content.html" %}</html>

content.html:

<h1>{% block title %}Title{% endblock title%}</h1>
<div>{% block content_body %}Content Body{% endblock content_body%}</div>

story.html

{% extends "base.html" %}
{% block title %}story.title{% endblock title %}
{% block content_body %}story.description{% endblock content_body %}

When rendering story.html, I'll get:

<html>
<h1>Title</h1>
<div>Content Body</div>
</html>

How would I render with the expected values?

1条回答
迷人小祖宗
2楼-- · 2019-03-14 17:13

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:

<html>{% block html %}{% endblock %}</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 %}

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).

查看更多
登录 后发表回答