Skip to content Skip to sidebar Skip to footer

Integrating And Rendering 2 Child Templates Into A Base Template - Django

I have a base template (index.html) and 2 child templates ipsum and need. I'm using blocks to try to integrate the 2 children into the base. base.html

Solution 1:

You should ask the first child to extend the 2nd child which will extend base html. This is how you extend multiple child templates in django.

Hence your code should look like this:

index.html

<html>
<body>
  {% block 'body1' %}
  {% endblock %}
  {% block 'body2' %}
  {% endblock %}
</body>
</html>

ipsum.html

{% extends 'index.html' %}
{% block 'body1' %}
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>
{% endblock %}

need.html

{% extends 'ipsum.html' %}
{% block 'body2' %}
    <p>Quo usque tandem abutere, Catsdsilina, patientia nostra?</p>
{% endblock %}

views.py

defindex(request):
    return render_to_response('need.html',context_instance=RequestContext(request))

so need need.html will first be rendered, it will look for ipsum.html and when ipsum.html is rendered, it will look for index.html

Alternatively

If you will like to do inclusion instead of extension, I recommend using the Django Sekizai library http://django-sekizai.readthedocs.org/en/latest/ . It includes custom tags such as {% include 'xx.html' %} that will render the 2nd child template in your first child if needed.

Cheers, BioBirdMan

Here is a working example:

http://biobirdman.com/stacktest/nestedtemplate/

Solution 2:

One way to achieve this would be to only have one block in the base template, and override that block in each child template, like:

base.html:

<html><body>

      {% block 'content' %} gets overridden {% endblock %}

  </body></html>

child1.html:

{% extends'base.html' %}

{% block 'content' %}

    <h1> Page1 </h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

{% endblock %}

child2.html:

{% extends'base.html' %}

{% block 'content' %}

    <h1> Page2 </h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit</p>

{% endblock %}

Post a Comment for "Integrating And Rendering 2 Child Templates Into A Base Template - Django"