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

Using multiple data sources for an underscore template

本文关键字:数据源 下划线      更新时间:2024-01-11

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