Django - “包含”一个块在几个模板?模板标签?还有什么? [英] Django - "Include" a block in several templates? Template tag? Something else?

查看:106
本文介绍了Django - “包含”一个块在几个模板?模板标签?还有什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个统计信息块,我想在几个地方可用:用户的个人资料页面和一个包含用户列表的搜索页面。

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.

重复此块时最好的方法是什么?
我来自PHP背景,在PHP中,传递一些简单的参数将是一个简单的包括。在django中,我基本上希望能够调用以下内容:

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 %}

其中用户是包含所有用户信息的对象。我在想一个简单的模板标签,但是这个块是很大的,我不想把eveything放在一个模板标签中。

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.

非常感谢!

推荐答案

include template tag



您可以包含模板参数

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



模板继承



但最好的在所有模板中重复一个块的方法是使用基本模板base.html:

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 %}

请参阅有关模板继承的文档

最后,另一个好的选择是使 inclusion_tag ,它允许在实际模板包含之前钩住一些python上下文处理。

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

这篇关于Django - “包含”一个块在几个模板?模板标签?还有什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆