Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 Inheritance with Blocks and Includes

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?

like image 694
Devin Avatar asked Feb 12 '12 01:02

Devin


People also ask

What is block content in Jinja?

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.

What is template inheritance Jinja?

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.


1 Answers

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

like image 199
Alex Morega Avatar answered Nov 15 '22 23:11

Alex Morega