在高级自定义模板标签中获取请求上下文

时间:2018-09-02 13:26:28

标签: django django-templates internationalization

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

@register.simple_tag(takes_context=True)

custom template tags - inclusion tags的官方文档。

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

我要做的是扩展i18n {% trans %}标记,以便在使用gettext之前先在数据库中查找翻译。我需要从自定义模板标签访问request.Language

1 个答案:

答案 0 :(得分:2)

Django doc of custom template tags中,还可以为海关标签添加 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 %}