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.

5
  • Have you place javascript code in phtml or js file?
    – Kul
    Dec 2, 2016 at 8:23
  • This is in a custom.js loaded via XML, as it runs on all pages.
    – Asitis
    Dec 2, 2016 at 8:26
  • hence the title of my question ;)
    – Asitis
    Dec 2, 2016 at 8:38
  • Ok have you check this ?
    – Kul
    Dec 2, 2016 at 8:54
  • Hm no. That's based on Magento1 and Prototype (which I believe is no longer part of Mag2) but it did lead me to this answer, but it seems outdated nowadays too magento.stackexchange.com/questions/38039/…
    – Asitis
    Dec 2, 2016 at 9:09

2 Answers 2

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.