dragan atanasov

// blog about developer thoughts

Translate JavaScript strings in Magento [1.7+]

Feb 18, 2014magento

Magento is very good in managing translations on multi language shops, out of the box you get very easy translation using CSV files, but that works great only in PHP. Translating JavaScript strings like validation messages or alert boxes was little tricky and required adding inline JavaScript code which is not very good idea because it can be lost later with editing/upgrading template files or changing template.

Since Magento CE 1.7 we have a tool that allows easy translation of JavaScript strings. Just add jstranslator.xml file in the etc folder of your module.

    <foo-unique-id translate="message" module="foo_bar">
    <bar-unique-id translate="message" module="foo_bar">

-You can add translation strings for both admin and frondend

After this you can add and use translations in CSV files like always:

"Foo","Le Foo"
"Bar","Le Bar"

-For example here is French translation: app/locale/frFR/FooBar.xml

And later just use Translator.translate('Some string') to get appropriate translated string.


-just to make things clearer


You can still translate JavasSript strings without inline coding(except code for translating) in older versions of Magento, just you need to use Translator object:

<script type="text/javascript">
Translator.add('Foo', '<?php echo $this->__('Foo'); ?>');

Note: If you are getting ’Translator is not defined’ error. Check if you have the var Translator in your HTML source code. If not please add following line in template/page/html/head.phtml file:

<?php echo $this->helper('core/js')->getTranslatorScript(); ?>