django - 在高级自定义模板标签中获取请求上下文
问题描述
在 Django 中,简单和包含模板标签允许获取请求上下文
@register.simple_tag(takes_context=True)
自定义模板标签的官方文档- 包含标签。
但是,对于自定义标签,我看不到这是如何完成的。
我想做的是扩展 i18n{% trans %}
标签,在使用gettext
. 我需要request.Language
从自定义模板标签访问。
解决方案
从自定义模板标签的 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 %}
推荐阅读
- python - 如何制作逼真的 2D 玩家动作(跳跃、流动性……)
- python - 如何实现管理员审批系统以在 pythondjango 中发布博客
- python - 使用 boto3 将 gzip 文件上传到 S3 存储桶的最佳方式
- c# - 如何将 MessagePack-CSharp 与字符串 JSON 一起使用?不是 CLI,是 neuecc/MessagePack-CSharp
- sql - 多个结果时的情况
- python-3.x - jupyter notebook 错误权限被拒绝:无标题 IPYNB
- python - 有人可以解释一下我在将这个数据框转换为 Python 中的字典时在做什么
- html - 如何使用 :hover 在 div 中更改我的箭头颜色?
- javascript - 尝试使用类组件中的方法更新状态中的道具
- selenium-webdriver - 在 Azure DevOps 管道上运行的 SpecFlow BDD UI 测试