【问题标题】:Using multiple data sources for an underscore template为下划线模板使用多个数据源
【发布时间】:2015-02-17 20:31:16
【问题描述】:

我想使用i18n(用于require.js)库根据用户的语言将我存储的字符串加载到资源文件中。 我使用了this 方法,因为我在我的项目中同时使用了主干和require.js。

假设这是我的模板,我想在其中使用翻译后的字符串。

    <h1><%= test.options.test %></h1> 
    <b> user_ud: <%= data.id %> </b>

使用从资源文件中获取的数据评估第一行。 但第二行是我想使用不同来源的数据的地方。

(默认资源文件)

define({
    'root': {
        'options': {
            'test': 'Yellow'
        }
    },
    "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 ) /// loads pre-compiled template ///         
                    $el.html(compiledTemplate);
                }else{
                    console.log(" [e] No template found. ");
                }
            });
        }
    });

    return TooltipView;
});

我想实现这个输出:

<h1> Yellow </h1> 
<b> id: 14 </b>

但我不确定如何将两个数据源放入一个模板中。

【问题讨论】:

    标签: javascript backbone.js i18next


    【解决方案1】:

    您可以将resource 和模型数据包装成一个新对象,该对象将成为模板中使用的根对象:

    var compiledTemplate = template['test']({
      i18n: resource,
      data: this.model.toJSON()
    });
    

    然后在模板中访问它们

    <h1><%= i18n.test.options.test %></h1> 
    <b> user_ud: <%= data.id %> </b>
    

    【讨论】:

    • 在我关闭计算机后我的脑海中突然出现了同样的问题,我今天早上想删除我的问题但是你更快,..你的答案确实是正确的。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2012-05-11
    • 2012-08-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多