Issue
I was looking in other questions.
- I know that Django allows to use built-in tags in the internal JavaScript code on HTML page, but it is a bad practice that a professional developer would not do;
- I know that Django does not allow to use built-in tags in the external JavaScript files. Differently of it, Go Hugo allows.
- I considered the question Django translations in Javascript files, but I do not know if it is a bad practice to generate the JavaScript with the same name but with with different language abbreviation, as
table-en.js
,table-fr.js
,table-pt-br.js
,table-pt-pt.js
, etc.
The small code, for example:
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++' }
];
I also need to translate the table columns:
firstHeader.textContent = 'Name of colour';
secondHeader.textContent = 'Preview of icons';
trHeader.appendChild(firstHeader);
trHeader.appendChild(secondHeader);
thead.appendChild(trHeader);
I want to translate 'List of colours and icon in'
, 'Name of colour'
and 'Preview of icons'
.
As Django does not allow to use the built-tag of translation in this file, how do you solve it?
I am sure if the question Django translations in Javascript files is the only solution and good or bad practice.
Solution
you can make this work creating functions inside a javascript file and import that file in the html. Afterwards, translate the objects you want inside your template, then pass the translated texts to the functions you created. There is no other way, don't worry about bad practices.
<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>
To change translations languages in the template see https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#switching-language-in-templates
Answered By - mendespedro
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.