djangodjango-templatesmultiple-inheritanceextendstemplate-inheritance

django template inheritance - views.py for multiple child templates


I am trying to create base.html and load several child templates named "nav.html", "contents.html" and "footer.html" on the base. I want to make all three child templates be loaded on the base.html page Whenever I visit /base.html.

base.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>{% block title %}{% endblock %}</title>
  </head>

  <body>
    <nav class="navbar">
      <div class="nav">
        {% block nav %}{% endblock %}
      </div>
    </nav>

    <div class="content">
      {% block contents %}{% endblock %}
    </div>

    <div class="footer">
      {% block footer %}{% endblock %}
    </div>
  </body>
</html>

nav.html:

{% extends "base.html" %}

{% block title %}Page Title{% endblock %}

{% block nav %}
    <p>Here goes the nav</p>
{% endblock %}

contents.html:

{% extends "base.html" %}

{% block contents %}
    <p>Here goes the contents</p>
{% endblock %}

footer.html:

{% extends "base.html" %}

{% block footer %}
    <p>Here goes the footer</p>
{% endblock %}

Right now, my views.py looks like:

from django.shortcuts import render
from django.template.response import TemplateResponse

def index(request):
    return TemplateResponse(request, "main/base.html")

Which does not load any of the three child templates, and if I load one of the child templates like

from django.shortcuts import render
from django.template.response import TemplateResponse

def index(request):
    return TemplateResponse(request, "main/nav.html")

I cannot load the other two child templates. How should I set the views.py file so that I can load all three child templates on base.html by loading only /base.html? (I think there is no location problem. Where I think I am stuck is how to properly set "views.py" to get the expected result.)


Solution

  • Within your blocks use the #include tag in your base.html template.

    {% block nav %}
        {% include "nav.html" %}
    {% endblock %}
    

    This way when you then extend a new template from base.html you'll just override what's in the blocks.