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

标签 django django-templates internationalization

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

@register.simple_tag(takes_context=True)

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

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

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

最佳答案

来自 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,它接受上下文并在标签内执行您的逻辑并从数据库返回翻译文本。如果它不在数据库中,返回一个 bool 值 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 %}

关于django - 在高级自定义模板标签中获取请求上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52137476/

相关文章:

c# - 没有获得基于 CurrentUICulture 的 .Resx

python - 如何在 Django 中获取模型实例保存到的数据库?

python - 需要 Django 用户输入步骤

javascript - Django 从模板写入上下文

javascript - ngx-translate 和 ngx-i18next 有什么区别

java - 为不同的语言环境定制 java.text 格式化程序

mysql - 如何使用 gitlab CI/CD 设置与 MySql 数据库的连接

python - Login_required Django 装饰器

ruby-on-rails - Rails 中 Django 模板的“无空间”等价物

python - 在 Django 中迭代特定组中的项目