[Fixed]-Django – "Include" a block in several templates? Template tag? Something else?

42👍

include template tag

You can include templates with arguments:

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}

Template inheritance

But the best way to repeat a block in all templates, is to have a base template say base.html:

<html>
...
    <div id="user-block">
        {% if request.user.is_authenticated %}
            hello {{ request.user }}
        {% else %}
            <a href="{% url acct_signup %}">Sign up!</a>
        {% endif %}
    </div>
 ...
    <div id="body">
        {% block body %}
        {% endblock %}
    </div>
 ...
 </html>

For example, the contact template could be as simple as:

{% extends 'base.html' %}

{% block body %}
    Contact use: foo@example.com
{% endblock %}

Refer to documentation on template inheritance for more.

inclusion_tag

Finally, another great option is to make an inclusion_tag, which allows to hook some python context processing before actual template inclusion.

👤jpic

1👍

You can write a custom template tag, which can render a specific template.
Refer Inclusion tags.

From the link: Another common type of template tag is the type that displays some data by rendering another template.

👤Rohan

Leave a comment