我意识到有一个实用程序django.utils.translation可以以某种方式翻译"Hola"中的"Hello",但我希望对确切的翻译有更多的控制。
现在,我的django项目正在使用View.py包装器实现多语言支持,该包装器用于渲染,并使用一些逻辑来确定用户的首选区域设置或返回到默认区域设置。
我的模板目前处于这种类型的结构中:
templates/en_US/index.html
templates/es_MX/index.html
如果templates/pt_pt/index.html不存在,那么一些逻辑会让它回到templates/en_US/index.html。
我想创建一个自定义标记/函数(https://docs.djangoproject.com/en/1.8/howto/custom-template-tags/)在我的模板层中,它可以将令牌转换为字符串,这样我就可以不再为每个区域设置维护一组模板文件。例如:
<h2> {% t 'index.welcome' %} </h2>
在美国,它将变成:
<h2> Welcome </h2>
在es MX中,它将变成:
<h2> Hola </h2>
所以我想我可以这样做:
from django import template
register = template.Library()
@register.simple_tag
def t(token):
# determine locale and look up the token and get its value
# in the appropriate locale file (with some fall-back logic)
但是我无法访问已注册标记中的请求对象,因此我无法确定查找区域设置所需的内容。
Django的国际化框架已经提供了所有这些功能以及更多功能,如本文所述:https://docs.djangoproject.com/en/1.8/topics/i18n/translation/
具体来说,模板中的翻译是通过反模板标签(如{% trans 'Welcome' %}
)完成的。
(正如我在上面的评论中所提到的)