2012-01-10 79 views
3

我有一个骨干视图,它将搜索结果呈现在下划线模板中。正如我想强调在结果中搜索词我在模板中的以下打印方法:如何将其他变量传入下划线模板

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(); 
    } 
}); 

回答

8

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

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

jquery extend函数让我把两个对象合并成一个。所以在你的情况下,你可以在模板化过程中将你的“searchTerm”和你的模型合并。

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

你的其他选择是将整个模型传递到你的模板功能和模板进行的下划线迭代。让我知道你是否需要更多的解释。

编辑:

这里是jquery extend

一个链接下划线也有和extend method如果你不使用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())); 
} 
+0

这似乎有点矫枉过正到我的结果合并一个新的对象,但经过考虑之后,似乎对这个问题的唯一解决方案,使用全局变量或内联模板到函数旁边,在那里声明searchTerm变量。 – 2012-01-10 21:31:01

+0

我同意这是一个非常奇怪的情况。您基本上将“searchTerm”从您的模型中拉出,迭代您的模型集合,然后将“searchTerm”重新绑定到集合中的每个项目。您始终可以将整个模型绑定到模板,而不是将其分开。然后将你的html包装在模板中的_.each()中。这只是偏好。祝你的项目好运:D – Mike 2012-01-10 21:39:22

+1

你能否在答案中显示你最后的建议。 – 2012-01-10 21:45:17