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

前端 未结 2 485
小鲜肉
小鲜肉 2020-12-29 10:21

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 th

2条回答
  •  死守一世寂寞
    2020-12-29 11:16

    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:

    
    ...
        
    {% if request.user.is_authenticated %} hello {{ request.user }} {% else %} Sign up! {% endif %}
    ...
    {% block body %} {% endblock %}
    ...

    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.

提交回复
热议问题