2012-09-24 43 views
2

我在我的視圖中使用.ejs模板。但由於某些原因,視圖不會加載給定的模板。它返回undefined。這裏的代碼:模板不加載在Backbone.js應用程序 - 使用Yeoman構建

sandplate2.applicationView = Backbone.View.extend({ 
    el: 'div', 

    template: _.template($("appl.ejs").html()), 

    initialize: function(){ 
    console.log("Application view initialize"); 

    _.bindAll(this, "render"); 

    this.render(); 
    }, 

    render: function(){ 
    console.log("Application view rendering"); 
    this.$el.html(this.template()); 
    return this; 
    } 
}); 

我必須配置其他東西來加載模板?

我使用Yeoman構建了我的應用程序。我使用init和主幹生成器。

僅供參考 - 我嘗試加載的模板使用腳本元素加載到index.html中。

回答

2

如果您使用Yeoman構建它,請查看app.js,看看您是否使用Backbone.LayoutManager。您可能需要更改配置以使EJS正常工作。默認情況下,我認爲它應該是期待Underscore模板。

我使用Handlebars,我更新了我的app.js看起來像這樣:

Backbone.LayoutManager.configure({ 
    manage: true, 

    paths: { 
    layout: "templates/layouts/", 
    template: "templates/" 
    }, 

    fetch: function(path) { 
    path = path + ".html"; 

    if (!JST[path]) { 
     $.ajax({ url: app.root + path, async: false }).then(function(contents) { 
     JST[path] = Handlebars.compile(contents); 
     }); 
    } 

    return JST[path]; 
    } 
}); 

我還添加了車把模塊的定義()調用,傳遞「把手」作爲參考。您可能需要爲EJS做類似的事情。

+0

真棒。今晚會試試這個。 – jsf

+0

順便說一句,你是如何安裝把手的?你有我可以看的樣品嗎?我運行yeoman安裝把手,它不會將它安裝在我的項目任何地方。 – jsf

+1

我將一個AMD版本的Handlebars(因爲我使用RequireJS)放到了scripts/libs文件夾中,添加了一個handlebars條目到config.js的'paths'部分,然後像上面提到的那樣編輯了Backbone.LayoutManager.configure 。 – JamesOR

0

請與yeoman 1.0beta一起使用最新的backbone genearator。 我們已經做了很多改進,包括Precompiling ejs templates。你不需要擔心模板,yeoman會預編譯併爲你加載。

下面提供了用於輸入視圖的示例生成代碼。

Todo.Views.InputView = Backbone.View.extend({ 

    template: JST['app/scripts/templates/input.ejs'], 

    render: function(){ 
     $(this.el).html(this.template()); 
    } 

}); 
0

約定拋開,它看起來像問題只是你的jQuery查找。

_.template($("appl.ejs")... 

$('appl.ejs')不是一個有效的DOM選擇,除非你有一個這樣的元素在您的index.html

<appl class="ejs"></appl> 

如果你正在嘗試的目標與jQuery你的模板,給它一個ID什麼是jQuery的可以找到像這樣:

<script type="text/template" id="appl"> 
    <div></div><!-- template html here --> 
</script> 

    // later... 
    $('#appl').html() 
    // will get your template html 

然而,正如其他人在自耕農提到,和require.js工作流程,你可以問require.js爲文本,您將獲取模板在創建下劃線模板之前將其作爲變量進行拋出。

相關問題