[Django]-Is dividing a template into parts and including each part bad?

7👍

Your approach is fine but you are doing this in wrong order. First of all the html starting <html> and ending tag </html> should not be split into different files, it is good to have it in base.html.

Below is an example of how to follow the breakup structure:

base.html

<html>
    <head>
        <!-- Some stuff here which should be included in all templates for example js or css -->
        {% block extra_css %}
            <!-- to included app-template dependent css -->
        {% endblock extra_css %}

        {% block extra_js %}
            <!-- to included app-template dependent js -->
        {% endblock extra_js %}

        {% block extra_head %}
            <!-- for anything else inside head -->
        {% endblock extra_head %}

    </head>
    <body>
        {% block menu %}
            <!-- Default menu here -->
            {% block extra_menu %}
                <!-- extend menu based on template -->
            {% endblock extra_menu %}
        {% endblock menu %}

        {% block content %}
            <div>This is good</div>
        {% endblock content %}

        {% include "footer.html" %}

        {% block bottom_js %}
            <!-- if you want to have manual js scripts at bottom -->
        {% endblock bottom_js %}
    </body>
</html>

Now base.html is all setup now lets suppose from another child template you want to override the base.html block content you will do:

child.html

{% extends "base.html" %}

{% block content %}
    <div>This is really good</div>
{% endblock content %}

So when the page will be loaded you will see this is really good instead of this is good (which was defined in base.html inside content block) because you just override it.

If you want that whatever inside the content block in base.html should also be preserved then you need to extend the block rather than overriding it completely by using method {{ block.super }}

child.html

{% extends "base.html" %}

{% block content %}
    {{ block.super }}
    <div>This is really good</div>
{% endblock content %}

Now you will see both this is good and this is really good. Hope this will clarify your concept and will lead you good.

Leave a comment