Tuesday, November 17, 2015

3 ways to Add JavaScript Translations in Magento

3 ways to Add JavaScript Translations in Magento

If you want to add translation in JavaScript code of your Magento module, there are three ways to achieve that. You can select any approach that suits your requirement the best.

Method 1: Direct Translation: In this method you can use the defalt Magento translation function to perform the translations. For example in your .phtml you can write the following code:

alert("<?php echo Mage::helper('core')->__('I have been translated.') ?>");

This is the simplest way to Translate JavaScript strings in Magento.

Method 2: Using Translator: Magento provides you the JavaScript Translator object to translate the strings which is used as follows:

alert(Translator.translate('I have been translated.'));

Before that you have to add the string in Translator as follows:

<script type="text/javascript">
Translator.add('I have been translated.','<?php echo Mage::helper('core')->__('I have been translated.')?>');

You have to add this new string in the translation csv file of your module. See how to add translation csv in your module.

Method 3: Using jstranslator.xml: Alternatively you can add the jstranslator.xml in your module under etc/ folder. This file contains all the string that you want to translate through JavaScript. Here is the sample file:

    <my_string translate="message" module="mymodule">
        <message>I have been translated.</message>
    <my_another_string translate="message" module="mymodule">
        <message>I want to be translated.</message>

Now in your template or JS file you can use:

alert(Translator.translate('I have been translated.'));



No comments: