How to properly translate strings in JavaScript
-
16-04-2021 - |
Question
Say I have a piece of custom JavaScript loaded in some pages of my store. This JavaScript serves the purpose of interactivity and can display some text. How would I make it multi-langual like I would with the __("string");
format in PHP?
Say i.e. I have this piece of JavaScript:
$('.readmorebutton').click(function() {
if (! $('.readmore').hasClass('open') ) {
$('.readmorebutton').text('Show less'); //How to translate?
} else {
$('.readmorebutton').text('Read More'); //How to translate?
}
});
note: JS is taken out of context and stripped down; the working of it is not the issue, the translating of the text
is.
Solution
Write your strings to be translated like so:
$.mage.__('Foobar')
$('.readmorebutton').click(function() {
if (! $('.readmore').hasClass('open') ) {
$('.readmorebutton').text($.mage.__('Show less')); //How to translate?
} else {
$('.readmorebutton').text($.mage.__('Read More')); //How to translate?
}
});
Magento then should use the same translation files as your PHP/HTML code.
Don't forget to clear caches and re-deploy static content afterwards.
OTHER TIPS
I made a easy solution:
let sometext = '<?php echo $this->__('text to be translated.'); ?>';
$('.readmorebutton').click(function() {
if (! $('.readmore').hasClass('open') ) {
$('.readmorebutton').text(sometext);
} else {
$('.readmorebutton').text('Read More');
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange