在 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/