John Dowling
John Dowling

Reputation: 612

Order of operations when parsing Django templates

I am trying to figure out how Django handles the order of operations when html templates are rendered.

Take the following as an example of what I am trying to answer.

I have a base template that "{% includes %}" a section of code that contains a "{% block %}" statement.

This base template is used in an "{% extends %}" and the "{% block %}" statement is overridden in this child template.

common.html

<div>
{% block content %}{% endblock %}
</div>

base.html

{% include common.html %}

child.html

{% extends 'base.html'%}
{% block content %}
..... some code
{% endblock %}

From my testing this block is not overridden as I would expect, am I doing something wrong or is this down to the order of operations in the Django template parsing.

Upvotes: 0

Views: 221

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599778

This isn't really to do with the order of operations as much as the definition of the include tag. From the docs:

The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process.

Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.

Upvotes: 1

Related Questions