【问题标题】:Marionette view's Handlebars template compiled once before useMarionette view 的 Handlebars 模板在使用前编译一次
【发布时间】:2013-03-27 00:07:20
【问题描述】:

我正在使用带有 Marionette.CompositeView 的 Handlebars 模板。模板定义为:

template : function (serializedData) {
    var templFn = Handlebars.compile(myTemplateDef);
    return this.templFn(serializedData);
}

在带有 Handlebars 的传统 Backbone 中,建议不要在每次渲染视图时编译模板,而是将编译后的模板存储为 View 属性,这样它只会编译一次,从而节省资源:

templFn : Handlebars.compile(myTemplateDef),

render : function () {
  var serializedData = this.model.toJSON();
  ...
  this.$el.append(this.templFn(serializedData);
}

但在 Marionette 的情况下,template() 的上下文是 window,我无法控制调用 template() 的方式/时间。

所以问题是:鉴于我们不想创建一个全局变量window.templFn,在木偶的情况下,有没有办法将模板编译与其使用分开?

【问题讨论】:

    标签: templates backbone.js marionette


    【解决方案1】:

    木偶有把手插件:https://github.com/asciidisco/Backbone.Marionette.Handlebars

    它可能不是完全最新的,但您至少应该能够看到他们如何处理模板的编译。

    一般来说,Marionette 提供了一个Marionette.RendererMarionette.TemplateCache 对象来允许一个模板被编译一次,并且只编译一次,然后从缓存的模板编译中重新渲染。

    【讨论】:

    • 谢谢,看起来很有希望。我会调查的。
    【解决方案2】:

    我刚开始使用 Marionette 就在 2 天前,我在 Marionette 之前的代码中使用了 Handlebars(纯骨干),然后我在 Marionette 中使用了这种方式:

    template : function(data) {
      if (typeof this.tplFun === 'undefined') {
        this.tplFun = Handlebars.compile($('#angry_cat-handlebars').html());
      }
      return this.tplFun(data);
    };
    

    或者您可以将 tplFun 添加到您的初始化函数中

    【讨论】:

      猜你喜欢
      • 2012-08-11
      • 2014-11-12
      • 2013-08-19
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      相关资源
      最近更新 更多