运行Marionette的Webpack应用程序中的外部模板

问题描述:

我正在用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

为了使用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

这是由于语法错误。我错误地将template散列嵌套在initialize ->方法中。回答我自己的问题,希望它能帮助某个人。