【问题标题】:Django, Template tags vs. Context ProcessorsDjango,模板标签与上下文处理器
【发布时间】:2020-04-12 17:38:55
【问题描述】:

我无法理解 django 模板中的模板标签和上下文处理器之间的区别。 我已经读过this question。但是我无法理解所有内容。

模板标签用于轻松处理、定制数据等,而上下文处理器用于获取完全不同的数据。我的理解正确吗?

我认为上下文处理器更易于使用,因为不需要{% load ~~ %}。是不使用上下文处理器的原因吗?是因为需要Heavy处理吗?

对不起,我的英语听不懂:(

等待您的答复!!

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    让我分享一下我使用模板标签和上下文处理器的方式。

    context_processors.py

    from billing.models import customerType
    
    def get_menu(request):
        customerTypes = customerType.objects.filter(active=True)
        item = []
        for customerType in customerTypes:
            item = {
                'name': customerType.name,
                'slug': customerType.slug
            }
            cp_customerType_list.append(item)
        return {'cp_customerType_list': cp_customerType_list}
    

    settings.py

    ...
    "context_processors": [
        ...
        "billing.context_processors.get_menu",
        ...
    ],
    ...
    

    customer_type_template_tag.py

    from django import template
    from django.http import request
    from billing.context_processors import get_menu
    
    register = template.Library()
    
    @register.inclusion_tag('billing/tags/customer_types.html')
    def get_customer_types_list():
        return get_menu(request)
    

    customer_types.html

    <ul class="slide-menu">
        {% for cp_customerType in cp_customerType_list %}
        <li>
            <a href="{% url 'billing_customer_list' customerType.slug=cp_customerType.slug %}">
                {{cp_customerType.name}}
            </a>
        </li>
        {% endfor %}
    </ul>
    

    base.html

    <!doctype html>
    ...
    <!-- at the top of the base.html page -->
    {% load customer_type_template_tags %}
    ...
    <!-- at the point of loading the customer types menu -->
    {% get_customer_types_list %}
    ...
    

    【讨论】:

    • 自包含数据和样式的 get_customer_types_list 现在可以拖放到任何页面上,并且会以相同的方式显示。
    【解决方案2】:

    将模板标签视为具有 UI 构建并准备在任何页面中使用的迷你页面。无需任何进一步修改,它将以相同的方式显示。如果您要使用上下文处理器在每个页面中提供数据,则必须编写 html 代码以使数据以您想要的方式显示。如果该数据需要出现在许多页面中,则必须在每个页面中重复 html 代码。

    【讨论】:

    • 举个有用的例子
    【解决方案3】:

    它们是两种不同的东西。上下文是您从视图传递到模板的数据,例如用户、表单、some_object 和 ...

    Django 模板标签是简单的 Python 函数,它们接受一个或多个值、一个可选参数、处理这些值并返回一个要在页面上显示的值。

    【讨论】:

      【解决方案4】:

      对于上下文处理器,当您需要使某些内容对所有模板全局可用时,最重要的是。例如,您可以要求像用户 is_authenticated?、is_admin?和 get_or_create group。它为我们提供全局操作

      【讨论】:

      • 谢谢你的简单解释!!我现在可以理解了。
      猜你喜欢
      • 2011-01-15
      • 2011-02-17
      • 2015-11-01
      • 2015-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-05
      • 2012-04-06
      相关资源
      最近更新 更多