2013-11-01 44 views
1

我想使用grunt-contrib-jst編譯我的下劃線模板,但它似乎不能正確渲染/保留變量。下面是一個模板看起來像正常:grunt contrib-jst渲染下劃線模板格式不正確

<script id="header-template" type="text/template"> 
    <h4><%= subhead %></h4> 
    <h1><span class="head-text"><%= head %></span> 
     <span class="subtext"><%= subtext %></span> 
    </h1> 
    <p></p> 
    </script> 

和這裏的什麼獲取通過咕嚕呈現:

this["JST"] = this["JST"] || {}; 

this["JST"]["templates/header.html"] = function(obj) { 
obj || (obj = {}); 
var __t, __p = '', __e = _.escape; 
with (obj) { 
__p += '<h4>' + 
((__t = (subhead)) == null ? '' : __t) + 
'</h4>\n<h1><span class="head-text">' + 
((__t = (head)) == null ? '' : __t) + 
'</span>\n <span class="subtext">' + 
((__t = (subtext)) == null ? '' : __t) + 
'</span>\n</h1>\n<p></p>'; 

} 
return __p 
}; 

下面是我如何設置我的咕嚕任務:

jst: { 
     compile: { 
     files: { 
      "scripts/templates/all.js": ["templates/*.html"] 
     } 
     } 
    } 

,當我嘗試利用模板:

var app = app || {}; 

app.HeaderView = Backbone.View.extend({ 
    el: '#header-container', 
    //template: _.template($('#header-template').html()), 
    template: JST['templates/header.html'](), //http://stackoverflow.com/questions/8366733/external-template-in-underscore 

    initialize: function(templateContent) { 
     this.render(templateContent); 
    }, 
    render: function(templateContent) { 
     this.$el.html(this.template(templateContent)); 
     return this; 
    } 
}); 

我得到這個錯誤:

Uncaught ReferenceError: subhead is not defined 

任何想法是錯誤的,如何保持我原來的模板格式?

回答

1

你說你是

[...] trying to use grunt-contrib-jst to compile my underscore templates

這正是發生了什麼。如果你看一下_.template docs,你會看到這一點:

The source property is available on the compiled template function for easy precompilation.

如果你這樣做與<script>

var t = _.template($('#header-template').html()); 
console.log(t.source); 

,你會在控制檯中看到那個醜陋的功能。

演示:http://jsfiddle.net/ambiguous/WjNGC/

因此,使用_.template然後傾倒編譯模板函數的source屬性的一個文件JST任務只是編譯你的模板;然後,當瀏覽器加載該JavaScript文件時,您將獲得已編譯的模板。

的結果是,你可以這樣說:

var html = JST['templates/header.html'](data); 

,並得到填充在0​​模板而不必編譯在瀏覽器中的模板。

+0

對不起 - 請參閱修改後的修改 - 我在執行此操作時遇到錯誤。變量「數據」似乎不可訪問。 – mheavers

+1

'template:JST ['templates/header.html']()'調用模板函數,你需要'template:JST ['templates/header.html']'(無函數調用圓括號)。然後'this。$ el.html(this.template(templateContent));'應該工作得很好。我的答案中的「數據」僅用於說明目的,您正在使用'templateContent' –

+0

謝謝!超級有用。 – mheavers