我将多语言Django应用程序从Django的模板引擎迁移到Jinja2。在模板中,我目前使用Django's language
template tag,即:
{% load i18n %}
<h1>{% trans 'Page title' %}</h1>
<ul>
{% for obj in object_list %}
{% language obj.language_code %}
<li><a href="{{ obj.get_absolute_url }}">{% trans 'view' %}: {{ obj.title }}</a>
{% endlanguage %}
{% endfor %}
</ul>
我们还使用i18n_patterns
,因此每个对象的网址也是特定于语言的。
我坚持如何将其转换为Jinja。我不能使用Django的i18n模板标签,也无法找到与Jinja等效的东西。
我还在查看Babel以帮助从模板中提取消息。因此,首选适用于Babel和Django的解决方案。
答案 0 :(得分:2)
我有这段代码在jinja2中切换语言。
def change_lang(request, lang=None, *args, **kwargs):
"""
Get active page's url by a specified language, it activates
Usage: {{ change_lang(request, 'en') }}
"""
path = request.path
url_parts = resolve(path)
url = path
cur_language = get_language()
try:
activate(lang)
url = reverse(url_parts.view_name, kwargs=url_parts.kwargs)
finally:
activate(cur_language)
return "%s" % url
在settings.py 中
TEMPLATES = [
{
"BACKEND": "django_jinja.backend.Jinja2",
'DIRS': [
os.path.join(BASE_DIR, 'templates/jinja'),
],
"OPTIONS": {
# Match the template names ending in .html but not the ones in the admin folder.
"match_extension": ".html",
"match_regex": r"^(?!admin/).*",
"newstyle_gettext": True,
"extensions": [
"jinja2.ext.do",
"jinja2.ext.loopcontrols",
"jinja2.ext.with_",
"jinja2.ext.i18n",
"jinja2.ext.autoescape",
"django_jinja.builtins.extensions.CsrfExtension",
"django_jinja.builtins.extensions.CacheExtension",
"django_jinja.builtins.extensions.TimezoneExtension",
"django_jinja.builtins.extensions.UrlsExtension",
"django_jinja.builtins.extensions.StaticFilesExtension",
"django_jinja.builtins.extensions.DjangoFiltersExtension",
],
'globals': {
'change_lang': 'drug.utils.change_lang'
},
"bytecode_cache": {
"name": "default",
"backend": "django_jinja.cache.BytecodeCache",
"enabled": False,
},
"autoescape": True,
"auto_reload": DEBUG,
"translation_engine": "django.utils.translation",
"context_processors": [
"dashboard.context_processors.auth",
# "django.template.context_processors.debug",
"django.template.context_processors.i18n",
# "django.template.context_processors.media",
# "django.template.context_processors.static",
# "django.template.context_processors.tz",
"django.contrib.messages.context_processors.messages",
]
}
},
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(BASE_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
},
},]
然后您可以在模板{{ _('Hello World') }}
答案 1 :(得分:2)
事实证明,通过编写自定义jinja2扩展(我将其基于example in the jinja2 docs)来实现这一点非常简单:
from django.utils import translation
from jinja2.ext import Extension, nodes
class LanguageExtension(Extension):
tags = {'language'}
def parse(self, parser):
lineno = next(parser.stream).lineno
# Parse the language code argument
args = [parser.parse_expression()]
# Parse everything between the start and end tag:
body = parser.parse_statements(['name:endlanguage'], drop_needle=True)
# Call the _switch_language method with the given language code and body
return nodes.CallBlock(self.call_method('_switch_language', args), [], [], body).set_lineno(lineno)
def _switch_language(self, language_code, caller):
with translation.override(language_code):
# Temporarily override the active language and render the body
output = caller()
return output
# Add jinja2's i18n extension
env.add_extension('jinja2.ext.i18n')
# Install Django's translation module as the gettext provider
env.install_gettext_translations(translation, newstyle=True)
# Add the language extension to the jinja2 environment
environment.add_extension(LanguageExtension)
使用此扩展程序切换活动翻译语言与在Django中执行此操作非常相似:
{% language 'en' %}{{ _('Hello World'){% endlanguage %}
唯一需要注意的是,当使用Django作为gettext提供程序并使用Babel作为消息提取程序时,告诉Babel在运行django
时将消息域设置为init/update/compile_catalog
非常重要。