JS翻譯老是有問題,經常會掉失譯文,這是由於JS模板裏的譯文是由js-translation.json提供,這個數據在static content deploy時被建立,把須要使用到的譯文加到裏面。它不會包含全部譯文,某個程序判斷加什麼譯文,但程序有無數的BUG,這時大概只能手動添加譯文了。javascript
<?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>
define( [ 'jquery', 'mage/translate' ], function( $, $t ) { var txt = $t( 'hello world!' ); var txt = $.mage.__( 'hello world!' ); } );
<span data-bind="i18n: 'Text'"></span>
<!-- ko i18n: 'Text'--><!-- /ko -->
以上方法仍是有可能會出問題的,我在2.0上實施過,會有20%的可能性會失效。那是由於整個項目是用requirejs來決定加載順序的,是外部引入的JS很容易requirejs調整加載順序,確保譯文JS優先於使用者JS準備完成。但放在模板上的沒法指定requirejs中的模塊名,因此須要轉爲外部。php
Controller php
html
namespace Infinity\Theme\Controller\Translation; class Index extends \Magento\Framework\App\Action\Action { public function execute() { $resultFactory = $this->_objectManager->create('Magento\Framework\Controller\Result\JsonFactory'); /* @var \Magento\Framework\Controller\Result\Json $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
java
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'); });