2

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.

Fabian Schmengler
  • 65,791
  • 25
  • 187
  • 421
Asitis
  • 1,247
  • 3
  • 17
  • 34

2 Answers2

5

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.

Eamonn
  • 508
  • 2
  • 10
0

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'); } });

AcidBurn
  • 45
  • 11