Translate JavaScript strings in Magento [1.7+]

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.

  1. <jstranslator>
  2. <foo-unique-id translate="message" module="foo_bar">
  3. <message>Foo</message>
  4. </foo-unique-id>
  5. <bar-unique-id translate="message" module="foo_bar">
  6. <message>Bar</message>
  7. </bar-unique-id>
  8. </jstranslator>

-You can add translation strings for both admin and frondend

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

  1. "Foo","Le Foo"
  2. "Bar","Le Bar"

-For example here is French translation: app/locale/fr_FR/Foo_Bar.xml

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

  1. alert(Translator.translate('Foo'));

-just to make things clearer

Bonus:

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:

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


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:

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