我想在这里更新一下答案,因为我只是在努力解决这个问题,并且我使用这个答案作为参考。
以下是我的发现:
这里的答案与当前版本有点过时了Mustache(这是可以理解的,因为它很旧)
-
小胡子.to_html现已弃用,但仍然作为简单的包装器存在小胡子渲染用于向后兼容。查看此链接 https://github.com/janl/mustache.js/blob/master/mustache.js#L550-L559.
此外,我发现压倒性的木偶.渲染器.渲染,如上面接受的答案所示,完全绕过了Marionette.TemplateCache层,这可能不是所需的行为。
这是该的来源木偶.渲染器.渲染 method:
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);
}
Source https://github.com/marionettejs/backbone.marionette/blob/master/src/marionette.renderer.js#L12-L29
正如你所看到的,它访问Marionette.TemplateCache.get方法和上面的答案对维护该功能没有任何作用。
现在开始我的解决方案(注意:上面的答案不一定是错误的;这只是我维护Marionette.TemplateCache layer):
正如上面的评论所建议的,覆盖编译模板反而:
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);
};
这是一个有效的 JSFiddle 作为证明 http://jsfiddle.net/aubricus/ktG52/.
在小提琴中,我也重写了Marionette.TemplateCache.loadTemplate证明它只被调用一次。函数体仅添加一些调试输出,然后重新实现大部分原始功能(减去错误处理)。