下面的代码使用工作正常Backbone.Marionette.ItemView
但没有Mustache
。
Backbone.Marionette.ItemView -没有胡子
我想使用相同的代码,但加载使用模板varaible Mustache
。
这里是我的代码:
Backbone.Marionette.ItemView -带髭
任何想法,为什么我的代码不能正常工作,为什么?
谢谢
下面的代码使用工作正常Backbone.Marionette.ItemView
但没有Mustache
。
Backbone.Marionette.ItemView -没有胡子
我想使用相同的代码,但加载使用模板varaible Mustache
。
这里是我的代码:
Backbone.Marionette.ItemView -带髭
任何想法,为什么我的代码不能正常工作,为什么?
谢谢
木偶假设默认使用UnderscoreJS模板。 只需简单地更换template
配置的观点是不够的。 您还需要更换渲染过程是如何工作的。
在您简单的例子,你只需要重写Marionette.Renderer.render
函数来调用小胡子,然后设置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"
});
请注意,您的jsfiddle仍然不会甚至当你在的地方把这个代码,因为工作GridView
依然采用了jQuery选择/字符串作为template
属性。 你需要与同类型的替换此template
函数返回小胡子。
http://jsfiddle.net/derickbailey/d7qDz/
I'd like to update the answer here a bit as I was just struggling with this, and I was using this answer as a reference.
Here are my findings:
The answer here is a bit out of date with the current version of Mustache (which is understandable as it's pretty old)
Additionally, I found overriding Marionette.Renderer.render, as in the accepted answer above, completely bypasses the Marionette.TemplateCache layer which may not be the desired behavior.
Here's the source for the Marionette.Renderer.render 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
As you can see it accesses the Marionette.TemplateCache.get method and the above answer does nothing to maintain that functionality.
Now to get to my solve (note: the above answer is not wrong necessarily; this is just my approach to maintain the Marionette.TemplateCache layer):
As the comments suggest above, override compileTemplate instead:
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);
};
Here's a working JSFiddle as proof.
In the fiddle, I've also overridden Marionette.TemplateCache.loadTemplate to demonstrate that it's only called once. The body of the function only adds some debug output and then re-implements most of the original functionality (minus error handling).