Mustache with Marionette.js
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.2/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.0/backbone-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.marionette/1.5.1-bundled/backbone.marionette.min.js"></script>
<script type="text/template" id="sample-template">
<h1>Hello x {{name}}!</h1>
</script>
<small id="load-count">Load Count: <span>0</span></small>
<small id="views-added">Views Added: <span>0</span></small>
<hr>
<div id="view1"></div>
<div id="view2"></div>
<div id="viewX"></div>
<div id="viewY"></div>
CSS
small {
font-size: 80%;
display: block;
}
JavaScript
/* ===========================
FIDDLE DEBUG HELPERS / VARS
=========================== */
var loadCount = 0;
var loadActions = 0;
var updateLoadActions = function (count) {
$('#views-added span').html(count);
}
var updateLoadCount = function (count) {
$('#load-count span').html(count);
}
/* ====================
MARIONETTE OVERRIDES
==================== */
// This just adds some debug output, you can safely ignore this bit.
Marionette.TemplateCache.prototype.loadTemplate = function (templateId) {
// debug only: ignore
updateLoadCount(++loadCount);
// Semi-implement original function (removed error handling for berevity)
var template = Marionette.$(templateId).html();
return template;
}
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);
};
/* ================
DEMO APPLICATION
================ */
var SampleView = Marionette.ItemView.extend({
template: "#sample-template"
});
var App = new Marionette.Application();
App.addRegions({
view1: '#view1',
view2: '#view2',
view3: '#viewX',
});
App.addInitializer(function () {
var model, model2, model3;
// refresh the template on screen a few times to prove
// the cache only calls load on the template once
model = new Backbone.Model({
name: 'Foo'
});
model2 = new Backbone.Model({
name: 'Bar'
});
model3 = new Backbone.Model({
name: 'Qux'
});
App.view1.show(new SampleView({model: model}));
// debug only: ignore
...