【问题标题】:using variables in i18n resource files在 i18n 资源文件中使用变量
【发布时间】:2017-04-28 17:31:24
【问题描述】:

大家好,

我正在使用i18n(用于require.js)库根据用户的语言从资源文件中加载我翻译的字符串。 我使用了this 方法,因为我在我的项目中同时使用了主干和require.js。但我还想为存储在 i18n 资源文件中的字符串添加一个参数/变量。

假设这是 i18n 资源文件

define({
    'root': {
        'options': {
            'test': 'Yellow {variable.x}'
        }
    },
    "en-us": true
});

现在我不确定是否可以传递参数来评估资源文件中的变量。

define(['underscore', 'backbone', 'models/model', 'templates/template' , 'i18n!nls/resource'], function ( _, Backbone, tModel, template, resource) {
    var TooltipView = Backbone.View.extend({
        el : $('#test'),

        initialize: function(options){
            this.model = new tModel();
        },

        render: function(){
            var $el = this.$el;
                if(template.length != 0){
                    var compiledTemplate = template['test']( resource, { variable: "14"} ) /// loads pre-compiled template ///          
                    $el.html(compiledTemplate);
                }else{
                    console.log(" [e] No template found. ");
                }
            });
        }
    });

    return TooltipView;
});

我想实现这个输出:

<h1> Yellow 14 </h1>

【问题讨论】:

标签: javascript backbone.js requirejs i18next


【解决方案1】:

正如@Evgeniy 建议的那样,我应该在这种情况下使用 sprintf 库。

解决办法:

模板:

<span> <%= sprintf( data.text, data.id ) %>  </span>

资源文件:

define({
    'root': {
        'options': {
            'test': 'Yellow %i'
        }
    },
    "en-us": true
});

那么鉴于我需要改变这个:

define(['underscore', 'backbone', 'models/model', 'templates/template' , 'i18n!nls/resource', 'sprintf'], function ( _, Backbone, tModel, template, resource, s_utils) {
...
..
var data = _.extend( resource, { id: 11 } , s_utils );  // this enabled me to use the sprintf function in my template file. 
var compiledTemplate = template['test']( data ) /// loads pre-compiled template ///          
                    $el.html(compiledTemplate);

..
    return TooltipView;
});

【讨论】:

    猜你喜欢
    • 2013-08-22
    • 2015-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    相关资源
    最近更新 更多