Search code examples
djangoincludeblock

Django - block tags in included templates don't work - Why?


This question is kinda similar to this one, except for one small change -

I have block tags in the parent.html, and some are filled in the calling template, some others in the included template. The included ones don't work. Eg:

#parent.html
<head>{% block head %}Parent head {% endblock %} </head>
<body> {% block body %} Parent body {% endblock %} 
</body>

#include.html

{%block body %} Child body {% endblock %}

#child.html
{% extends 'parent.html' %}

{% block head %}
Child head 
{% endblock %}

{% include 'include.html' %}

But this gives output : Child head Parent body

intsead of the desired :

Child head Child body

Any workarounds?


Solution

  • This :

    {% include 'include.html' %}
    

    is not included in any block, and will not be rendered, as you see in response.

    Modify your child.html in that way:

    #child.html
    {% extends 'parent.html' %}
    
    {% block head %}
    Child head 
    {% endblock %}
    
    {% block body %}
        {% include 'include.html' %}
    {% endblock %}
    

    if you want to define some html in both child.html and in include.html, then you should have:

    #child.html
    {% extends 'parent.html' %}
    
    ....
    
    {% block body %}
        {% include 'include.html' %}
        some child html...
    {% endblock %}
    

    and in include.html:

    {% block body %}
        {{ block.super }}
        some include html...
    {% endblock %}
    

    This will render:

    some child html
    some include html