为下划线模板使用多个数据源

Using multiple data sources for an underscore template

我想使用 i18n(对于 require.js)库根据用户的语言将我存储的字符串加载到资源文件中。 我使用了 this 方法,因为我在我的项目中同时使用了 backbone 和 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>

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

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

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

然后在模板中访问它们

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