2014-09-28 54 views
1

我正在使用jQuery,jQueryMobile一個應用程序,並強調模板,但我從來沒有過這樣的錯誤,我無法找到發生在模板中的變量:的ReferenceError:變量不與下劃線模板定義

self.$list = $("#list"); 
    var template = _.template('<%= foo %>', {foo: 'hello'}); 
    self.$list.html(template); 

錯誤:的ReferenceError:FOO沒有被定義

這是一個例子,如果我嘗試呈現類別列表我有同樣的感覺。

_.each(categories, function(category){ 
     console.log(category); //<-- ok 
     var template = _.template(self.$categoryTemplate.text(), category); 
     self.$list.append(template); 
    }); 

categoryTemplate:

<script id="category-template" type="text/template"> 
     <li><a href="#"><% = name %></a></li> 
    </script> 

我不明白你爲什麼不看變量在模板

回答

2

_.template調用返回一個函數,它接受一個對象與模板變量作爲第一個論點。

所以,你應該這樣做:

self.$list = $("#list"); 
var template = _.template('<%= foo %>')({foo: 'hello'}); 
self.$list.html(template); 

這:

_.each(categories, function(category){ 
    console.log(category); //<-- ok 
    var template = _.template(self.$categoryTemplate.text())(category); 
    self.$list.append(template); 
}); 
+0

非常感謝你,它的工作原理,但我不明白爲什麼上面不起作用。 – oscar 2014-09-28 15:12:05

+1

@oscar:最近更改了'_.template'接口,請參閱我對複製副本的回答以瞭解詳細信息。 – 2014-09-28 17:30:46