如何使用Backbone.Marionette.ItemView与Mustache

Lor*_*ard 8 mustache backbone.js marionette

以下代码使用Backbone.Marionette.ItemView但不是Mustache.

Backbone.Marionette.ItemView - 没有胡子

我想使用相同的代码,但加载模板变量使用Mustache.

这是我的代码:

Backbone.Marionette.ItemView - 与胡子

知道为什么我的代码不起作用,为什么?

谢谢

Aub*_*cus 14

我想在这里稍微更新答案,因为我正在努力解决这个问题; 我正在使用这个答案作为参考.

这是我的发现:

这里的答案与当前版本的Mustache有点过时(这是可以理解的,因为它已经很老了)

  • Mustache.to_html现已弃用,但仍然作为Mustache.render的简单包装器存在,用于向后compat.看看这个链接.

另外,我发现重写Marionette.Renderer.render,如上面接受的答案,完全绕过Marionette.TemplateCache层,这可能不是所需的行为.

这是Marionette.Renderer.render方法的来源:

render: function(template, data){

  if (!template) {
    var error = new Error("Cannot render the template since it's false, null or undefined.");
    error.name = "TemplateNotFoundError";
    throw error;
  }

  var templateFunc;
  if (typeof template === "function"){
    templateFunc = template;
  } else {
    templateFunc = Marionette.TemplateCache.get(template);
  }

  return templateFunc(data);
}
Run Code Online (Sandbox Code Playgroud)

如您所见,它访问Marionette.TemplateCache.get方法,上面的答案没有任何维护该功能.

现在来解决问题(注意:上面的答案不一定是错的;这只是我维护Marionette.TemplateCache层的方法):

正如上面的评论所示,改为覆盖compileTemplate:

Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate) {

    // Mustache.parse will not return anything useful (returns an array)
    // The render function from Marionette.Renderer.render expects a function
    // so instead pass a partial of Mustache.render 
    // with rawTemplate as the initial parameter.

    // Additionally Mustache.compile no longer exists so we must use parse.
    Mustache.parse(rawTemplate);
    return _.partial(Mustache.render, rawTemplate);
};
Run Code Online (Sandbox Code Playgroud)

这是一个有效的JSFiddle作为证明.

在小提琴中,我还重写了Marionette.TemplateCache.loadTemplate,以证明它只被调用一次.函数体仅添加一些调试输出,然后重新实现大多数原始功能(减去错误处理).


Der*_*ley 8

Marionette默认使用UnderscoreJS模板.仅仅替换template视图的配置是不够的.您还需要替换渲染过程的工作方式.

在您的简单示例中,您只需要覆盖Marionette.Renderer.render调用Mustache 的函数,然后将template视图设置为所需的字符串模板:


Backbone.Marionette.Renderer.render = function(template, data){
  return Mustache.to_html(template, data);
}

var rowTemplate = '{{ username }}{{ fullname }}';

// A Grid Row
var GridRow = Backbone.Marionette.ItemView.extend({
    template: rowTemplate,
    tagName: "tr"
});
Run Code Online (Sandbox Code Playgroud)

请注意,即使您将此代码放在适当位置,您的JSFiddle仍然无法工作,因为GridView仍然使用jQuery选择器/字符串作为template属性.你需要用相同类型的template函数替换它来返回胡子.

http://jsfiddle.net/derickbailey/d7qDz/

  • 这取决于您是否使用从DOM中选择模板的默认行为,或者将模板作为原始字符串提供.在这个问题的情况下,模板是一个原始字符串,所以重写`Renderer.render`更合适.但是,如果模板是DOM"<script>"标签,那么TemplateCache`creditTemplate`函数将是正确的选择. (2认同)