首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >教程:基于node.js库的i18n /聚合物L20n解决方案

教程:基于node.js库的i18n /聚合物L20n解决方案
EN

Stack Overflow用户
提问于 2016-02-28 00:22:31
回答 1查看 731关注 0票数 0

i18n在node.js web项目中的实现存在一个比较常见的问题。如果你想:

  1. 使用web组件(如聚合物)
  2. 对服务器端和客户端文件使用单个翻译文件。
  3. 翻译一些项目(比如动态创建的字符串)

由于Mozilla团队开发了全新的L20n库,这个问题可以很容易地解决。

EN

回答 1

Stack Overflow用户

发布于 2016-02-28 00:22:31

项目结构

首先,我创建了一个项目结构,它可以将我的文件分开保存,并按其目的分组:

代码语言:javascript
复制
.
+-- 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是一个用于用户界面l10n的聚合物组件。

安装

运行npm install l20n --save

目前的版本是3.5.1,它有一个小错误。l20n的主文件是./dist/compat/node/l20n.js,它有两个必需的变量,它们不在代码中任何地方使用,但在启动时可以压碎应用程序,因为它们只在库的设备依赖项中提到。为了避免这种情况,我将它们直接注释到库代码中:

代码语言:javascript
复制
//var string_prototype_startswith = require('string.prototype.startswith');
//var string_prototype_endswith = require('string.prototype.endswith');

翻译文件

我在/public/locales/文件夹中创建了翻译文件,名为app.ru.l20napp.en.l20n。根据L20n规则,文件的内容如下:

代码语言:javascript
复制
<foo "Foo translation">
<bar "Bar translation">
<register[$variant] {
    infinitive: "Register now!"
}>

Node.js + L20n

现在是为L20n创建节点模块的时候了。在我的例子中,app_modules\app-l20n-node\index.js的代码如下所示:

代码语言:javascript
复制
'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。但这一切都取决于项目。

代码语言:javascript
复制
var l20n =  require('../../app_modules/app-l20n-node');

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

聚合物+ L20n

现在我们应该为L20n创建一个聚合物组分。

首先,将库和翻译文件链接到html <head>中。

代码语言:javascript
复制
<script src="/node_modules/l20n/dist/compat/web/l20n.js"></script>
<link rel="localization" href="/locales/app.{locale}.l20n">

现在,是时候创建一个具有新行为的聚合物组件app-l20n.html了。

代码语言:javascript
复制
<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>

不,因为新的行为已经准备好了,我们可以在我们的定制聚合物组件中实现它。您可以通过聚合物行为或使用L20n自定义标记属性功能获得编程翻译。

代码语言:javascript
复制
<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>

希望这个小小的教程会有帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35677198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档