20

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?

Devin
  • 2,113
  • 2
  • 22
  • 28
  • 3
    Where is @ArminRonacher when you need him - I have a feeling that this is caused by `include "content.html"` overriding the contents of the identically named blocks in `story` even though `story` is overriding `base` - but I don't see anything in the documentation to indicate that this is to be expected. – Sean Vieira Feb 22 '12 at 04:31
  • You should be looking at **macros** in Jinja2. I think this [SO question](https://stackoverflow.com/questions/2104957/in-jinja2-how-can-i-use-macros-in-combination-with-block-tags) is related to your queries. – ranendra Feb 12 '12 at 03:01

1 Answers1

15

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

Alex Morega
  • 4,132
  • 1
  • 24
  • 25
  • this is the proper solution for templates check django templates they do a similar thing to understand the concept. – Bedros Jun 24 '15 at 18:50