Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Locale language for Javascript in Magento

Tags:

magento

We can config in Magento to set locale language and using function $this->__(string $test) to translate.

How about this feature but for javascript? For example, when I use validation.js and when getting some errors it will show the message with the locale language which I set.

The validation.js file is located at: src/js/prototype/prototype.js

In inside the file we will see something:

Validation.addAllThese([
    ['validate-select', 'Please select an option.', function(v) {
                return ((v != "none") && (v != null) && (v.length != 0));
            }],
    ['required-entry', 'This is a required field.', function(v) {
                return !Validation.get('IsEmpty').test(v);
            }],
    ['validate-number', 'Please enter a valid number in this field.', function(v) {
                return Validation.get('IsEmpty').test(v) || (!isNaN(parseNumber(v)) && !/^\s+$/.test(parseNumber(v)));
            }]
]

So, how could I translate the messages This is a required field.,Please select an option.?

like image 813
vietean Avatar asked Jul 09 '26 13:07

vietean


2 Answers

I'm not sure if that's what you're asking, but the translations of th javascript messages are set in app/code/Core/Mage/Core/Helper/Js.php -> _getTranslateData() and is called in app/design/package/ theme/template/page/html/head.phtml <?php echo $this->helper('core/js')->getTranslatorScript() ?>

I've just need that myself, let me refrase:

  1. in the phtml you add the strings you need to translate:

    <script type="text/javascript">
        //<![CDATA[
            Translator.add('String to translate', '<?php echo $this->__('String to translate'); ?>');
        //]]>
    </script>
    
  2. in your javascript file, use:

    Translator.translate('String to translate');
    
  3. now you can use your csv translations files

like image 190
OSdave Avatar answered Jul 13 '26 15:07

OSdave


The correct method to add Javascript translations and avoid mixing PHP and JS is to add a jstranslator.xml file in your module.

The content of the file should be something like this:

<jstranslator>
    <my-message translate="message" module="mymodule">
        <message>My Original Message in Base Language</message>
    </my-message>
</jstranslator>

Then simple use yout own module's translation csv files to translate those strings.

Its worth mentioning that if you intend to translate core validation massages, those are already located in Mage_Core.csv translation file. You should create the corresponding translation file for your locale or customize the translations via the translate.csv file in your theme as usual.

like image 38
barbazul Avatar answered Jul 13 '26 17:07

barbazul