2013-08-22 28 views
0

我正在讀的應用程序的源代碼,我看到這行代碼:這個代碼是如何工作的.html(_模板()({})。)

$('#div1').html(_.template($('#div2').html())({Id: app.Id(id)})); 

我能理解$( '#div1')。html(),但爲什麼這行代碼可以傳遞兩個()代碼塊?它看起來不正確。 .html()可以帶兩個()塊嗎?

.html(_.template()());

回答

3

這是因爲_.template()返回一個函數,那麼我們呼籲與第二組返回功能()

var fn = _.template(sometemplate);//it gives a parsed template which is a function 
fn(data);//it merges the data and the template to generate the html 
0

這就是所謂的插值,並且使用正確的方法是像

var template = _.template("Hello {{ name }}!"); 
template({name : "Mustache"}); 
=> "Hello Mustache!" 

一樣

var template = _.template("Hello {{ name }}!")({name : "Mustache"}); 
=> "Hello Mustache!" 

http://underscorejs.org/#template