2014-10-06 67 views
0

我正在用Webpack設置應用程序並使用Backbone Marionette運行前端。我設法讓應用程序腳本運行[在AMD模塊中,在App模塊內的Controller中生成LayoutView],但我無法弄清楚的是模板運行Marionette的Webpack應用程序中的外部模板

在過去,我使用了Underscore模板,但是webpack更喜歡Jade和Handlebars。我切換到玉而我的LayoutView返回錯誤:

Uncaught UndefinedTemplateError: Cannot render the template since it is null or undefined.

當我安慰註銷呈現玉模板,我得到:<div class="glossary-container"></div>

下面是評論我的LayoutView代碼:

Marionette = require 'marionette' 
AppLayoutTemplate = (require 'templates/appLayoutTemplate.jade')() 
console.log AppLayoutTemplate 

class AppLayoutView extends Marionette.LayoutView 
    initialize: -> 
    template: AppLayoutTemplate 
    regions: 
     glossaryContainer: '.glossary-container' 
+0

牽線木偶中的任何視圖都需要編譯模板來呈現數據。默認情況下 - 下劃線編譯爲函數,該函數將在使用JSON模型渲染時調用。如果您需要實施其他模板引擎支持,則必須重新編寫Marionette.Renderer – Evgeniy 2014-10-06 06:48:00

回答

0

爲了使用Handlebars作爲Marionette的模板引擎,您需要重寫Marionette中的一些方法。

我建議你木偶內加載模板和使用某種類型的緩存:

首先重寫Marionette.TemplateCache.prototype.loadTemplate

Marionette.TemplateCache.prototype.loadTemplate = function (yourTemplateId) { 

    var yourTemplate, 
     url = 'your/path/to/templates' + yourTemplateId + '.html'; 

    if (Handlebars.templates && Handlebars.templates[yourTemplateId]) { 
     // from cache 
     yourTemplate = Handlebars.templates[yourTemplateId]; 
    } else { 
     // from remote resource 
     Backbone.$.ajax({ 
     async : false, 
     url  : url, 
     success : function (templateHtml) { 
      yourTemplate = templateHtml; 
     } 
    }); 
    } 
    return yourTemplate; 
}; 

和重寫Marionette.TemplateCache.prototype.compileTemplate

Marionette.TemplateCache.prototype.compileTemplate = function (yourTemplate) { 
    if ($.isFunction(yourTemplate)) { 
     return yourTemplate; 
    } else { 
     return Handlebars.compile(yourTemplate); 
    } 
}; 

此負載您的視圖後如:

Marionette = require 'marionette' 
    class AppLayoutView extends Marionette.LayoutView 
     initialize: -> 
     template: 'path_to_your_template/without_extension' 
     regions: 
      glossaryContainer: '.glossary-container' 

這將適用於把手。我不熟悉翡翠,但我相信它應該是一樣的。

+0

Vahan,感謝您的回答。這對未來確實有幫助。不幸的是,我的解決方案是我的一個愚蠢的語法錯誤。將「模板」散列嵌入到初始化方法中時,它應該位於根目錄下。對於任何遇到同樣問題的人,我將在下面回答我自己的問題。 – btburton42 2014-10-06 08:02:33

0

這是由於語法錯誤。我錯誤地將template散列嵌套在initialize ->方法中。回答我自己的問題,希望它能幫助某個人。

相關問題