Magento 添加翻译的方法(translate.js)

Magento 添加翻译的方法(translate.js)
2016年5月17日 Edited 2022年12月7日 浏览量 17 1 min read
Magento 添加翻译的方法(translate.js)

我们在开发magento多语言模板的时候,经常会遇到一些需要翻译的文本,有些我们可以简单得通过Mage::helper('yourmodule')->__('Translated text') 方法来实现,但是很多时候,特别是在js文件中遇到需要翻译的文本,就比较棘手了,这篇magento博客中,我们一起来看一下几种在magento中常用的翻译方法。

第一种是大部分magento开发者都知道的一种通过php添加文本翻译的方式,如下:


echo $this->__('Text to translate'); //这个方法是Mage_Core_Block_Abstract类中声明的 echo Mage::helper('somemodule/somehelper')->__('Text to translate'); // 由Mage_Core_Block_Abstract类声明的 echo $this->__('There are %s things here', $this->countThingsHere()); //与前面两句的区别在于,这句话中添加了一个动态变量

但是有些时候我们需要在JavaScript种添加一句翻译,该怎么办?当然如果是在模版文件中的JavaScript,你可以这样来写,这种方式跟上面说的第一种是基本相同的。 


<script type="text/javascript">
    confirm("<?php echo $this->__('Are you sure?') ?>");
</script>

第二种方式是上面这种写法的升级版,使用magento自带的Translator对象来添加。主要代码一共就两句:
第一句是Translator.add()方法,通过这个方法将我们想要翻译的语句加入到我们的翻译对象;
第二句是Translator.translate()方法,通过这个方法输出的文字就是我们想要得到的翻译后的文字。
具体实现方法如下: 


<script type="text/javascript">
    Translator.add('Some text to translate', '<?php echo Mage::helper('yourmodule')->__('Translated text') ?>');
    //添加一条翻译 
    alert(Translator.translate('Some text to translate')); 
    //返回一个alert()“翻译后的文本”;
</script>

 但是很多时候,你想要翻译的文本是在一个JavaScript文件中,而不是一个phtml模版文件中。在这种情况下,就是我们要讲到的第三种方式,我们可以使用PHP翻译方法。在这里你可以将你需要翻译的内容添加到当前模块的配置(etc)文件目录下的jstranslator.xml文件中。格式如下:


<jstranslator>
    <unique-id1 translate="message" module="yourmodule">
        <message>Some text to translate</message>
    </unique-id1>
    <unique-id2 translate="message" module="yourmodule">
        <message>Some other text</message>
    </unique-id2>
</jstranslator>

添加完成后,你就需要按照正常的添加翻译的步骤来你的翻译文件中添加要翻译的内容。以上步骤都完成后,你就可以直接在你的JavaScript文件中编辑或输出要翻译的内容了。


alert(Translator.translate('Some text to translate')); 

 以上代码输出了一句'Some text to translate'的翻译文件,如果这句话能够与你的翻译文件匹配上,那么就会输出对应的翻译。上面第三种翻译方法的优点在于翻译文本时不需要寄托于phtml模板文件或者Translator.add()方法,并且这个方法非常灵活。我们需要修改翻译的话,直接修改后缀名为.csv的翻译文件就可以了。

注意:上面的方法在magento1.7.0.0版本之前是不被支持的。

Previous article:
Next article:
Comments
发表评论,留下你的足迹
我们不会公开你的邮箱地址

是否允许我们在发布新内容或者进行促销活动向您发送消息?

Remind me later

Thank you! Please check your email inbox to confirm.

Oops! Notifications are disabled.

© 2014-2023 www.magease.com. All Rights Reserved. 寰云网络 版权所有    鲁ICP备 14014975号-1