I've translated some text in a javascript file with translation.js, I've done it the following way:
I've defined the translator.
define([
'mage/translate',
];
After that, I translated my text.
 $.mage.__('excl. VAT')
And added the translation in the CSV file.
The strange thing is, that sometimes it get's translated and sometimes not...
Did I miss something?
5 Answers 5
Best approach for this would be to use 'domReady!' in your define to make sure document is fully loaded once translation is applied.
define([
 'jquery',
 'underscore',
 'domReady!'
], function (,ドル _) {...}
- 
 So you don't needmage/translateat all?Black– Black2024年12月11日 15:14:48 +00:00Commented Dec 11, 2024 at 15:14
I wrote a post here regard to my the same issue. You can read to understand why it happens and how to fix https://mrvts.wordpress.com/2018/07/19/magento-2-javascript-translation-sometime-translate-sometime-not-work-why-and-how-to-fix/
it throw error if you use __ so follow below code
require([
 'jquery', // jquery Library
 'mage/translate'
 ], function(,ドル$t){ 
 alert($t('Enter Your message here'));
 });
You must use $.mage.__('excl. VAT') as it will be automatically parsed by an internal magento code and generate a JSON file in pub/static folder 
eg : pub/static/frontend/Magento/Luma/fr_FR/js-translation.json
BUT be aware that Magento will only parse js and html files. So if you use this $.mage.__('...') in phtml files it will not be translated.
it's about timing the translation. Magento had the same Problem in the Checkout or the Catalog in early Versions.
Here is an example: In an old Version, the Add to Cart Button was not translated anymore after adding the product to cart. The old Version had the translation in the initialization function:
while the new version has the translation in the handler function
Since all Javascript resources are loaded asynchronously, it may happen, that your component is loaded before the translation component is initialized.
The solution is, to translate the text as late as possible. For example, instead of being translated the Initialization function, it could be translated in a getText() function which is bound to the HTML element.
You should also take a look at the file pub/static/frontend/Your/Theme/<language>/js-translation.json (or something similar)
This File should contain all translations that are used in the theme's Javascript files and should contain your own translation. It gets regenerated if you delete it (at least in developer mode) and is also cached in the local storage of the browser.
- 
 The second link doesn't work anymore. Please explain what was thereBlack– Black2025年05月22日 16:05:02 +00:00Commented May 22 at 16:05
Explore related questions
See similar questions with these tags.