簡體   English   中英

教程:基於L20n庫的node.js / Polymer i18n解決方案

[英]Tutorial: solution for node.js / Polymer i18n based on L20n library

node.js Web項目中實現i18n是一個相當常見的問題。 如果您要執行以下操作,問題似乎更加嚴重:

  1. 使用網絡組件(例如Polymer
  2. 將單個轉換文件用於服務器端和客戶端文件
  3. 以編程方式翻譯某些項目(例如動態創建的字符串)

多虧Mozilla團隊開發了全新的L20n庫 ,這個問題可以很容易地解決。

項目結構

首先,我創建了一個項目結構,該結構將文件分開存放,並按用途分組:

.
+-- app.js
+-- piblic
|   +-- locales
|       +-- app.ru.l20n
|       +-- app.en.l20n
|
+-- node_models
|   +-- l20n 
|
+-- bower_components
|   +-- Polymer libraries
|
+-- app_modules
|   +-- app-l20n-node
|       +-- index.js
|
+-- app_components
    +-- app-l20n
        +-- app-l20n.html
    +-- app-custom-component
        +-- app-custom-component.html

這個想法很簡單: app-l20n-node用作本地化所有服務器端作業的模塊, app-l20n是用戶界面app-l20n的Polymer組件。

安裝

運行npm install l20n --save
當前版本是3.5.1,並且有一個小錯誤。 l20n的主文件是./dist/compat/node/l20n.js ,它具有兩個必需的變量,這些變量在代碼中的任何位置均未使用,但可能會在啟動時破壞應用程序,因為它們僅在庫的Devdependency中提及。 為了避免這種情況,我只是在庫代碼中對它們進行了注釋:

//var string_prototype_startswith = require('string.prototype.startswith');
//var string_prototype_endswith = require('string.prototype.endswith');

翻譯文件

我在/public/locales/文件夾中創建了翻譯文件,命名為app.ru.l20napp.en.l20n 根據L20n規則,文件內容如下所示:

<foo "Foo translation">
<bar "Bar translation">
<register[$variant] {
    infinitive: "Register now!"
}>

Node.js + L20n

現在是時候為L20n創建節點模塊了。 在我的情況下, app_modules\\app-l20n-node\\index.js的代碼如下:

'use strict';
const L20n = require('l20n');
var path = require('path');

module.exports = function(keys, lang){

    const env = new L20n.Env(L20n.fetchResource);

    // Don't forget nice debug feature of L20n library
    env.addEventListener('*', e => console.log(e));

    // I suppose that I'll always provide locale code for translation, 
    // but if it would not happen, module should use preset 
    var langs = [];
    if(!lang) {   
        // you should define locales here
        langs = [{code: 'ru'}, {code: 'en'}]
    } else {
        langs = [{code: lang}]
    }

    // set context, using path to locale files
    const ctx = env.createContext(langs, 
                    [path.join(__dirname, '../../public/locales/app.{locale}.l20n')]);

    const fv = ctx.formatValues;

    return fv.apply(ctx, keys);
};

現在,我們可以在node.js代碼中使用此模塊,並按鍵和語言環境的要求獲取翻譯。 我使用硬express-sessions代替硬編碼的語言環境,並將用戶定義的語言環境存儲為會話屬性req.session.locale 但這一切都取決於項目。

var l20n =  require('../../app_modules/app-l20n-node');

l20n(['foo','bar'], 'en')
    .then((t)=>{
        console.log(t); // ["Foo translation", "Bar translation"]
    });

聚合物+ L20n

現在,我們應該為L20n創建一個Polymer組件。
首先,添加庫並將翻譯文件的鏈接添加到您的html <head>

<script src="/node_modules/l20n/dist/compat/web/l20n.js"></script>
<link rel="localization" href="/locales/app.{locale}.l20n">

現在該創建具有新行為的Polymer組件app-l20n.html了。

<script>

    /**
     * Create namespace for custom behavior or use existing one.
     */
    window.MB = window.MB || {};

    MB.i18n = {

        /**
         * Use l20n.js to translate certain strings
         * @param component A Polymer component, usually "this.translate(this, props);"
         * @param props An array of keys to translate: strings or arrays.
         */
        translate: function(component, props) {
            var view = document.l10n;
            var promise = view.formatValues.apply(view, props);
            promise.then(function(args){
                for (var i in args){

                    var prop = props[i];

                    // strings with parameters represented by arrays: 
                    // ["string", {param: value}]
                    if (Array.isArray(prop)) {

                        // get property name - usually the same, as translation key
                        // so the object would have properties obj.Foo and obj.Bar
                        var propName = prop[0];

                        // if it is needed to create multiple translations of the same 
                        // string in one component, but with different parameters, 
                        // the best way is to use suffix: 
                        // ["string", {param: value}, "_suffix"]
                        if (prop.length == 3) propName = propName + prop[2];

                        component.set(propName, args[i]);
                    }

                    // common strings
                    else component.set(prop, args[i]);

                }
            });
        }
    };
</script>

不可以,因為新行為已經准備就緒,我們可以在自定義的Polymer組件中實現它。 您可以通過Polymer Behavior或使用L20n自定義標簽屬性功能以編程方式獲得翻譯。

<link rel="import" href="/bower_components/polymer/polymer.html">
<link rel="import" href="/bower_components/gold-email-input/gold-email-input.html">
<link rel="import" href="/bower_components/paper-button/paper-button.html">

<link rel="import" href="/app_components/app-l20n/app-l20n.html">

<dom-module id="app-custom-component">
    <template>
        <gold-email-input
            auto-validate
            required
            name="email"
            value="{{Foo}}"
            label="{{Bar}}">
        </gold-email-input>

        <paper-button onclick="regFormSubmit(event)">
            <iron-icon icon="perm-identity"></iron-icon>
            <span data-l10n-id="Register" data-l10n-args='{"variant": "infinitive"}'></span>
        </paper-button>
    </template>
    <script>
        function regFormSubmit(event){}
        Polymer({
            is: 'app-custom-component',
            behaviors: [
                MB.i18n
            ],
            ready: function(){
                this.$.passwordValidator.validate = this._validatePasswords.bind(this);

                // add your component properties to array. They can be simple like in this example, or
                // more complex, with parameters: ["Some_key", {param: "xxx"}].
                // you can even translate the same string in different properties, using custom suffix:
                // ["Some_key", {param: "yyy"}, "_suffix"] and place it in template with shortcut: {{Some_key_suffix}}
                var translateProps = ["Foo", "Bar"];

                // now translate, using behavior
                this.translate(this, translateProps);
            }
        });
    </script>
</dom-module>

希望本小教程對您有所幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM