andreas
andreas

Reputation: 117

Include Templates in Django. Am i doing it right?

PROBLEM:
I want to include serveral Templates into another Template, which gets initially rendered.

MY APPROACH:
Render index.html, which extends base.html and includes the other templates (include_body.html, include_head.html)

base.html:

<html>
    <head>
        {% block head %}{% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

index.html:

{% extends 'base.html' %}   
{% block head %}{% include 'include_head.html' %}{% endblock %}
{% block body %}{% include 'include_body.html' %}{% endblock %}

include_head.html (add content to the HTML head Element):

<script src="./static/js/map.js"></script>

include_body.html (add content to the HTML body Element):

<p>Hallo World!</p>

views.py (render index.html on request):

# ...
def index(request):
    return render(request, 'index.html')

QUESTION:
My Approach is working, but i am not confident about it. Espacially splitting up the head and body parts feels wrong. Is there a better way to do it? How can i avoid using include_head.html together with include_body.html, and instead use a single include.html?

Upvotes: 0

Views: 79

Answers (1)

BriceP
BriceP

Reputation: 508

It depends on what you need. I see 2 cases :

  • if for any reason I could have two or more base templates (like base.html and base_mobile.html, for example), which have to share some parts (like most infos), I would do this in base_mobile :
<html>
    <head>
        <script src="./static/js/mobile.js"></script>
        {% include 'include_head.html' %}
    </head>
    ...
</html>

And have the same for base.html, but without the mobile.js inclusion.

  • If the include_head is only used in one file, I see no reason not to write its content directly in that file.
<html>
    <head>
        <script src="./static/js/map.js"></script>
    </head>
    ...
</html>

Upvotes: 1

Related Questions