由于 Django 不允许在其他文件中使用 built-it 标签,如何解决 translation/localisation of JavaScript 外部文件?

How to solve the translation/localisation of JavaScript external files since Django does not allow built-it tags in other files?

我正在查看其他问题。

小码,例如:

var preTtitle = 'List of colours and icon in';

const styles = 
[
  { name: 'adwaita-plus', title: ' ' + preTtitle + 'Adwaita++' },
  { name: 'suru-plus', title: ' ' + preTtitle + 'Suru++' },
  { name: 'suru-plus-ubuntu', title: ' ' + preTtitle + 'Ubuntu++' },
  { name: 'yaru-plus', title: ' ' + preTtitle + 'Yaru++' }
];

我还需要翻译 table 列:

firstHeader.textContent = 'Name of colour';
secondHeader.textContent = 'Preview of icons';

trHeader.appendChild(firstHeader);
trHeader.appendChild(secondHeader);

thead.appendChild(trHeader);

我想翻译 'List of colours and icon in''Name of colour''Preview of icons'

由于Django不允许在这个文件中使用翻译的内置标签,请问如何解决?

我确定问题 Django translations in Javascript files 是否是唯一的解决方案以及好的或坏的做法。

您可以在 javascript 文件中创建函数并将该文件导入 html。之后,在模板中翻译您想要的对象,然后将翻译后的文本传递给您创建的函数。没有别的办法,不用担心不好的做法。

<script src="{% static 'js/translation_helpers.js' %}"></script>
<script>
    let frenchText = {% translate "something in french" %}
    functionYouCreated(translatedText, 'fr')
    let englishText = {% translate "something in english" %}
    functionYouCreated(translatedText, 'en')
</script>

要更改模板中的翻译语言,请参阅https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#switching-language-in-templates

我 运行 昨天遇到了这个问题,有人提出了更好的解决方案。实际上,您可以在 JavaScript 文件中使用 t运行slate 文本,而无需在 HTML 模板中获取 t运行slations。

Django T运行slation 为您提供了 JavaScriptCatalog,这允许您使用 gettext() 来 t运行slate 您的 js 文本,就像您所做的一样在你的观点中。

urls.py

from django.views.i18n import JavaScriptCatalog

urlpatterns = [
    path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'),
]

index.html

<script src="{% url 'javascript-catalog' %}"></script>

script.js

// In this example your body will get the translated version of "Hello"
document.body.innerHTML = gettext('Hello');

如何生成 t运行slation 文件:

django-admin makemessages -d djangojs -l es

这里的区别在于您将在命令中添加 -d djangojs。

完成 t运行slation 后,您可以像编译模板和视图一样编译消息 t运行slation:

django-admin compilemessages

Django 文档: https://docs.djangoproject.com/en/4.0/topics/i18n/translation/#internationalization-in-javascript-code

提供解决方案的问题:

@hendrikschneider 提供的解决方案:

Most of the work will be done by django. Follow their documentation: https://docs.djangoproject.com/en/4.0/topics/i18n/translation/#internationalization-in-javascript-code

A little further down on the page is also documented how to generate the language file for your javascript code. You will have two language files later, one for your django application and one for your javascript code.

https://docs.djangoproject.com/en/4.0/topics/i18n/translation/#creating-message-files-from-javascript-source-code