magento2 translate

发布时间:2019-08-04 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了magento2 translate脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

模板中添加翻译

JS翻译总是有问题,常常会掉失译文,这是因为JS模板里的译文是由js-translation.json提供,这个数据在static content deploy时被创建,把需要使用到的译文加到里面。它不会包含所有译文,某个程序判断加什么译文,但程序有无数的BUG,这时大概只能手动添加译文了。

<?php
// key 对应 JS 或 ko 模板中 i18n 的内容,value 为译文
$_translations = [
    'Text one to translate',
    'Text two to translate'
];
 
$_translations_data = [];
foreach($_translations as $_trans) {
    $_translations_data[$_trans] = __($_trans);
}
?>
<script>
    require( [
        'jquery',
        'mage/translate'
    ], function( $ ) {
        $.mage.translate.add( <?php echo Zend_Json::encode( $_translations_data ) ?> );
    } );
</script>

JS 中调用译文

define( [
    'jquery',
    'mage/translate'
], function( $, $t ) {
    VAR txt = $t( 'hello world!' );
    var txt = $.mage.__( 'hello world!' );
} );

ko 模板中调用译文

<span data-bind="i18n: 'Text'"></span>
<!-- ko i18n: 'Text'--><!-- /ko -->

以上方法还是有可能会出问题的,我在2.0上实施过,会有20%的可能性会失效。那是因为整个项目是用requirejs来决定加载顺序的,是外部引入的JS很容易requirejs调整加载顺序,确保译文JS优先于使用者JS准备完成。但放在模板上的无法指定requirejs中的模块名,所以需要转为外部。

Controller php

namespace InfinityThemeControllerTranslation;

class Index extends MagentoFrameworkAppActionAction {

    public function execute()
    {
        $resultFactory = $this->_objectManager->create('MagentoFrameworkControllerResultJsonFactory');
        /* @var MagentoFrameworkControllerResultJson $result */
        $result = $resultFactory->create();
        $result->setData(['translations' => $this->translations()]);
        return $result;
    }

    private function translations() {
        $_translations = [
            'Name on Card',
            'Credit Card Number',
            'Expiration Date',
            'Card Verification Number',
            'Place Order',
            'Credit Card Information',
            'What is this?',
            'Switch/Solo/Maestro Only',
            'Issue Number'
        ];
        $_translations_data = [];
        foreach($_translations as $_trans) {
            $_translations_data[$_trans] = __($_trans);
        }

        return $_translations_data;
    }

js


define(['jquery',
    'mage/translate',
    'text!../../../../../../../../theme/translation/index',
    'jquery/ui'], function ($, $t, translation_json) {
    'use strict';

    $.mage.translate.add( eval('['+translation_json+']')[0].translations );
    
    $t('Name on Card');
});

参考

http://devdocs.magento.com/gu...

脚本宝典总结

以上是脚本宝典为你收集整理的magento2 translate全部内容,希望文章能够帮你解决magento2 translate所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。