Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - "Include" a block in several templates? Template tag? Something else?

I have a little statistics block that I want to be available in several places: the profile page of a user, and a search page with a list of users.

What would be the best way to proceed in repeating this block? I come from a PHP background, and in PHP it would be a simple include with passing some simple arguments. In django, I basically want to be able to call something like :

 {% stats_block user %}

Where user is the object containing all the user info. I was thinking about a simple template tag, but the block is pretty big and I don't want to put eveything in one line in the template tag.

Thanks a lot!

like image 724
Alb Dum Avatar asked Aug 27 '12 13:08

Alb Dum


2 Answers

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: [email protected]
{% 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.

like image 125
jpic Avatar answered Oct 13 '22 00:10

jpic


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.

like image 45
Rohan Avatar answered Oct 13 '22 00:10

Rohan