Question

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?

Was it helpful?

Solution

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 ($, _) {...}

OTHER TIPS

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:

https://github.com/magento/magento2/blob/628687b491d2d95e164388bb2f4b97be41a1e211/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js#L23

while the new version has the translation in the handler function

https://github.com/magento/magento2/blob/develop/app/code/Magento/Catalog/view/frontend/web/js/catalog-add-to-cart.js#L121

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.

it throw error if you use __ so follow below code

require([
    'jquery', // jquery Library
    'mage/translate'
   ], function($,$t){ 
         alert($t('Enter Your message here'));

    });

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/

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top