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

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

问题描述

我有一个小统计块,我想在几个地方提供它:用户的个人资料页面,以及一个包含用户列表的搜索页面.

重复此块的最佳方法是什么?我来自 PHP 背景,在 PHP 中这将是一个简单的包含,并传递一些简单的参数.在 Django 中,我基本上希望能够调用类似的东西:

 {% stats_block user %}

其中 user 是包含所有用户信息的对象.我正在考虑一个简单的模板标签,但块非常大,我不想把所有东西都放在模板标签的一行中.

非常感谢!

解决方案

include template tag

您可以包含带参数的模板:

{% 包含 "name_snippet.html" 和 person="Jane" greeting="Hello" %}

模板继承

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

...<div id="用户块">{% if request.user.is_authenticated %}你好{{ request.user }}{% 别的 %}<a href="{% url acct_signup %}">注册!</a>{% 万一 %}

...<div id="body">{% 块体 %}{% 结束块 %}

...

例如,联系人模板可以很简单:

{% 扩展 'base.html' %}{% 块体 %}联系方式:foo@example.com{% 结束块 %}

有关更多信息,请参阅模板继承文档.

inclusion_tag

最后,另一个不错的选择是制作 inclusion_tag,它允许在实际包含模板之前挂钩一些 Python 上下文处理.

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!

解决方案

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.

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

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆