The following code works fine using Backbone.Marionette.ItemView
but not Mustache
.
Backbone.Marionette.ItemView - no Mustache
I would like to use the same code but loading the template varaible using Mustache
.
Here is my code:
Backbone.Marionette.ItemView - with Mustache
Any idea why my code does not work and why?
Thanks
Marionette assumes the use of UnderscoreJS templates by default. Simply replacing the
template
configuration for a view isn't enough. You also need to replace how the rendering process works.In your simple example, you only need to override the
Marionette.Renderer.render
function to call Mustache, and then set thetemplate
of your views to the string template that you want:Note that your JSFiddle still won't work even when you put this code in place, because the
GridView
is still using a jQuery selector/string as thetemplate
attribute. You'll need to replace this with the same type oftemplate
function to return mustache.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's 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:
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:
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).