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?
All the block tag does is tell the template engine that a child template may override those placeholders in the template. In your example, the base template (header. html) has a default value for the content block, which is everything inside that block. By setting a value in home.
The most powerful part of Jinja is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. Sounds complicated but is very basic.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With