如何将附加变量传递到下划线模板中

How to pass additional variables in to underscores templates

本文关键字:下划线 变量      更新时间:2023-09-26

我有一个主干视图,它在下划线模板中呈现搜索结果。由于我想在结果中突出显示搜索项,我在模板中有以下打印方法:

print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')

它与aspected一样工作,但我必须在全局命名空间中设置searchTerm变量才能完成这项工作。我想知道是否有一种方法可以在打印方法中访问我的视图模型,所以我可以这样写:

print(someKey.replace(searchTerm, '<b>' + this.model.get('searchTerm') + '</b>')

或者,我可以在渲染函数中将searchTerm设置为局部变量,并在模板中访问它。

以下是整个主干视图:

var searchTerm;
var SearchResultView = Backbone.View.extend({
    initialize: function() {
        this.model.bind('change:rows', this.render, this);
        this.model.bind('change:searchTerm', this.clear, this)
    },
    template: _.template("<tr><td><% print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')); %></td></tr>", this),
    render: function() {
       searchTerm = this.model.get('searchTerm')
        _.each(this.model.get('rows'), function(row) {
            this.el.append($(this.template(row.doc)));
        }, this)
    },
    clear: function(){
        this.el.empty();
    }
});

我不确定我是否完全理解你的问题。但是,我沿着这些线做了一些事情,将多个对象传递到我的模板函数中。

 $(this.el).html(_.template(html)($.extend({}, this.model.toJSON(), App.lists.toJSON())))

jquery扩展函数允许我将两个对象合并为一个对象。因此,在您的情况下,您可以在模板期间将"searchTerm"与您的模型合并。

_.template(html)($.extend({}, row.doc, {"searchTerm": searchTerm}))

您的另一个选择是将整个模型传递到模板函数中,并在模板中执行下划线迭代。如果你需要更多的解释,请告诉我。

编辑:

以下是jquery扩展的链接

如果您不使用jquery ,下划线也有和扩展方法

编辑编辑:

这只是给你举一个我第二个建议的例子。可能需要一些调整来加入你的,但这就是想法。

template: _.template("
    <% _(rows).each(function(row) { %>
        <tr><td><% print(someKey.replace(searchTerm, '<b>' + searchTerm + '</b>')); %></td></tr>
<% } %>
"),
render: function(){
    this.el.append(this.template(this.model.toJSON()));
}