首页 > 解决方案 > 在高级自定义模板标签中获取请求上下文

问题描述

在 Django 中,简单和包含模板标签允许获取请求上下文

@register.simple_tag(takes_context=True)

自定义模板标签的官方文档- 包含标签

但是,对于自定义标签,我看不到这是如何完成的。

我想做的是扩展 i18n{% trans %}标签,在使用gettext. 我需要request.Language从自定义模板标签访问。

标签: djangodjango-templatesinternationalization

解决方案


自定义模板标签的 Django 文档中,也可以添加takes_context海关标签

import datetime
from django import template

register = template.Library()


@register.simple_tag(takes_context=True)
def current_time(context, format_string):

    #use "context" variable here
    return datetime.datetime.now().strftime(format_string)


我不确定如何在这种特定情况下覆盖现有标签:(
无论如何,我的建议是,创建一个simple_tag接受上下文并在标签内执行逻辑并从数据库返回翻译文本。如果不是在数据库中,返回一个布尔值False。现在在模板中,使用if标签检查这些东西。

from django import template

register = template.Library()


@register.simple_tag(takes_context=True)
def is_db_available(context):
    # access your context here and do the DB check and return the translation text or 'False'
    if translation_found_in_DB:
        return "Some translation text"
    return False

并在模板中

{% load custom_tags %}
{% load i18n %}
{% is_db_available as check %} 
{% if check %}  <!-- The if condition  -->
    {{ check }}
{% else %}
    {% trans "This is the title." %} <!-- Calling default trans tag  -->
{% endif %}

推荐阅读