【问题标题】:get request context in Advanced custom template tags在高级自定义模板标签中获取请求上下文
【发布时间】:2019-02-07 18:52:15
【问题描述】:

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

@register.simple_tag(takes_context=True)

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

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

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

【问题讨论】:

    标签: django django-templates internationalization


    【解决方案1】:

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

    【讨论】:

    • 这不起作用,你为标签函数使用了错误的参数,它可以接受两个参数(上下文,字符串)而不是 3 个(内容,解析器,令牌)事实上引发的错误是“没有收到参数的值:'token'”
    • @uri.lazar 是的。这是正确的。现在我已经更新了答案。请检查并尝试一下
    • @uri.lazar 你试过了吗?
    猜你喜欢
    • 2012-05-04
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2015-01-20
    • 1970-01-01
    • 2010-11-17
    • 2018-10-13
    • 1970-01-01
    相关资源
    最近更新 更多