django翻译模板中的变量内容

发布于 2024-11-17 19:48:28 字数 530 浏览 2 评论 0原文

我正在使用 {% trans %} 模板标签。 Django 文档说:

{% trans %} 模板标记可转换常量字符串(用单引号或双引号括起来)或变量内容:

<块引用> {% trans“这是标题。” %} {% 反式 myvar %}

https://docs.djangoproject.com/en/ 4.0/topics/i18n/translation/#translate-template-tag

我发现不可能执行 {% trans myvar %} 因为 myvar 根本没有出现在 django.po 文件中运行 makemessages 命令后。

难道是我用错了?有人可以帮我解决这个问题吗?

I'm using {% trans %} template tag. Django docs say:

The {% trans %} template tag translates either a constant string (enclosed in single or double quotes) or variable content:

{% trans "This is the title." %}
{% trans myvar %}

https://docs.djangoproject.com/en/4.0/topics/i18n/translation/#translate-template-tag

I found it impossible to do {% trans myvar %} because myvar simply doesn't show up in django.po file after running makemessages command.

Am I using it wrong? Could some help me with this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

过度放纵 2024-11-24 19:48:28

您可以使用 blocktrans本例中的 模板标记:

{% blocktrans %} This is the title: {{ myvar }} {% endblocktrans %}

You can use the blocktrans template tag in this case:

{% blocktrans %} This is the title: {{ myvar }} {% endblocktrans %}
一直在等你来 2024-11-24 19:48:28

{% trans myvar %} 正常工作。因此,请检查您的 PO 文件以确保 myvar 的值位于 PO msgid 中。

<title>{% trans myvar %}</title>

例如,如果 myvar 包含 "Some Publisher",您可以在 PO 文件中写入以下内容:

msgid "Some Publisher"
msgstr "কিছু প্রকাশক"

同时确保您已运行:

python manage.py compilemessages

{% trans myvar %} just works. So check your PO file to make sure that the value of myvar is in PO msgid.

<title>{% trans myvar %}</title>

For example if myvar contains "Some Publisher" you can write the following in the PO file:

msgid "Some Publisher"
msgstr "কিছু প্রকাশক"

Also make sure you have ran:

python manage.py compilemessages
开始看清了 2024-11-24 19:48:28

Django 无法猜测该变量中的内容,因此您必须通过添加英语 (msgid) 和本地化 (msgstr) 字符串来自行翻译它。

Django can't guess what is in that variable, so you have to translate it yourself by adding both the english (msgid) and the localized (msgstr) strings.

情痴 2024-11-24 19:48:28

我的经验是,变量翻译本身不能在模板中工作。然而,当变量的内容已知时,我找到了一个合适的解决方案(我的意思是它们不是自由文本,而是您在数据库中设置的一组选择)。

您需要在视图或过滤器标记中强制翻译

总结一下:

  1. 在模板中使用 blocktrans
  2. 强制转换变量
    • 您可以在已标记为转换的上下文中设置变量
    • 或使用过滤器来翻译它们
  3. .po 文件中生成翻译

故事是这样的:

views.py

def my_view(request):
    return render(request, 'i18n_test.html', {'salutation':"Hola"})

templates/i18n_test.html

...
{% blocktrans %}{{ salutation }}{% endblocktrans %}
...

当我渲染模板时,无论当前语言是什么,它总是显示 Hola

为了强制翻译,在视图中我们需要使用ugettext。

def my_view(request):
    return render(request, 'i18n_test.html', {'salutation':ugettext("Hola")})

然而,并不总是可以访问该视图。所以我更喜欢使用这样的过滤器。

templatetags/i18n_extras.py

@register.filter(name='translate')
def translate(text):
  try:    
    return ugettext(text)

模板变为

...
{% blocktrans s=salutation|translate %}{{ s }}{% endblocktrans %}
...

并根据当前语言生成 Hola、Hello、Ciao、Salut

缺点(如 docs 中指出的)是 makemessages 不会自动包含这些翻译,因此我们需要手动包含它们。在 django.po 文件中:

locales/en/django.po

...
msgid "Hola"
msgstr "Hello"
...

My experience here is that variable translation does not work in templates on its own. However I came to a suitable solution when the content of the variables is known (I mean that they are not free text, but a set of choices you set in the database).

You need to force the translation in the view or in a filter tag.

To sum up:

  1. Use blocktrans in your templates
  2. Force variables to be translated
    • You either set variables in context that are already marked for transtalion
    • or use a filter to translate them
  3. Generate translations in .po file

The story is like this:

views.py

def my_view(request):
    return render(request, 'i18n_test.html', {'salutation':"Hola"})

templates/i18n_test.html

...
{% blocktrans %}{{ salutation }}{% endblocktrans %}
...

And when I render the template it always shows Hola whichever the current language is.

To force the translation, in the view we need to use ugettext.

def my_view(request):
    return render(request, 'i18n_test.html', {'salutation':ugettext("Hola")})

However it is not always possible to access the view. So I prefer to use a filter like this.

templatetags/i18n_extras.py

@register.filter(name='translate')
def translate(text):
  try:    
    return ugettext(text)

And the template becomes

...
{% blocktrans s=salutation|translate %}{{ s }}{% endblocktrans %}
...

And produces Hola, Hello, Ciao, Salut depending on the current language.

The disadvantage (as pointed out in the docs ) is that makemessages does not automatically include these translations, so we need to include them manually. In django.po file:

locales/en/django.po

...
msgid "Hola"
msgstr "Hello"
...
寄意 2024-11-24 19:48:28

您可以在 python 代码中翻译变量,如下所示 settings.SITE_NAME

from django.conf import settings
from django.utils.translation import ugettext_lazy as _

def processor004(request):
 my_dict = {
    'site_id004': settings.SITE_ID,
    'site_name004': _(settings.SITE_NAME),
    'installed_apps004': settings.INSTALLED_APPS,
    'embedded_widget004': settings.EMBEDDED_WIDGET,
    'base_template004': settings.BASE_TEMPLATE,
}

return my_dict

You can translate the variable in the python code like here for settings.SITE_NAME:

from django.conf import settings
from django.utils.translation import ugettext_lazy as _

def processor004(request):
 my_dict = {
    'site_id004': settings.SITE_ID,
    'site_name004': _(settings.SITE_NAME),
    'installed_apps004': settings.INSTALLED_APPS,
    'embedded_widget004': settings.EMBEDDED_WIDGET,
    'base_template004': settings.BASE_TEMPLATE,
}

return my_dict
似狗非友 2024-11-24 19:48:28

在模板中创建自己的标签

from django.utils.translation import ugettext as _

@register.simple_tag
def trans2(tr, *args, **kwargs):
    # print(':', kwargs)
    trans = _(tr)
    trans_str = trans.format(**kwargs)
    return trans_str

{% trans2 columns_once.res_data.message with value=columns_once.res_data.recommend%}

在 django.po 中

#: default_content.py:136
msgid "_audit_recommend_speed"
msgstr "Рекомендованная скорость до {value} сек"

make own tags

from django.utils.translation import ugettext as _

@register.simple_tag
def trans2(tr, *args, **kwargs):
    # print(':', kwargs)
    trans = _(tr)
    trans_str = trans.format(**kwargs)
    return trans_str

in template:

{% trans2 columns_once.res_data.message with value=columns_once.res_data.recommend%}

in django.po

#: default_content.py:136
msgid "_audit_recommend_speed"
msgstr "Рекомендованная скорость до {value} сек"
云仙小弟 2024-11-24 19:48:28

作为解决方法,您可以在 { 之间收集 {% trans %}(django 3.0 及更低版本)或 {% trans %}(django 3.1 及更高版本)标签% comment %}{% endcomment %} 在一个模板中。如果您有不止一种语言的 po 文件,这将节省您重复键入相同 msgid 的精力。

{% comment %}
{% trans "Tea" %}
{% trans "Clothes" %}
{% endcomment %.}

确保在输入上述代码后运行 django-admin makemessages --all 。

As one workaround, you can collect {% trans %}(django 3.0 and below) or {% translate %}(django 3.1 and above) tags between {% comment %} and {% endcomment %} in one template. This will save your efforts to repeat typing the same msgid should you have more than one language po file.

{% comment %}
{% trans "Tea" %}
{% trans "Clothes" %}
{% endcomment %.}

Make sure you run django-admin makemessages --all after putting the aforementioned code.

影子是时光的心 2024-11-24 19:48:28

这是一个复杂而优雅的解决方案,如果您要翻译模型字段中的值,可能会有所帮助:http://django-modeltranslation.readthedocs。 org

“Modeltranslation

modeltranslation 应用程序用于将现有 Django 模型的动态内容翻译为任意数量的语言,而无需更改原始模型类。”

It's a complex elegant solution that may help if you are translating values from model fields: http://django-modeltranslation.readthedocs.org

"Modeltranslation

The modeltranslation application is used to translate dynamic content of existing Django models to an arbitrary number of languages without having to change the original model classes."

淤浪 2024-11-24 19:48:28

对我来说,当我的 Django 项目目录之外有 TEMPLATES.DIRS 时,就会发生这种情况。将模板提取到项目目录中解决了问题。

To me, this happened when I had the TEMPLATES.DIRS outside my Django project directory. Fetching the templates into the project directory solved the problem.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文