Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Integrates Handlebars with Marionette. First attempts to load pre-compiled templates, then by selector, and finally via XHR.
/**
Usage: Just include this script after Marionette and Handlebars loading
IF you use require.js add script to shim and describe it in the requirements
*/
(function(Handlebars, Marionette) {
Marionette.Handlebars = {
path: 'templates/',
extension: '.handlebars'
};
Marionette.TemplateCache.prototype.load = function() {
if (this.compiledTemplate) {
return this.compiledTemplate;
}
if (Handlebars.templates && Handlebars.templates[this.templateId]) {
this.compiledTemplate = Handlebars.templates[this.templateId];
}
else {
var template = this.loadTemplate(this.templateId);
this.compiledTemplate = this.compileTemplate(template);
}
return this.compiledTemplate;
};
Marionette.TemplateCache.prototype.loadTemplate = function(templateId) {
var template, templateUrl;
try {
template = Marionette.$(templateId).html();
}
catch (e) {}
if (!template || template.length === 0) {
templateUrl = Marionette.Handlebars.path + templateId + Marionette.Handlebars.extension;
Marionette.$.ajax({
url: templateUrl,
success: function(data) {
template = data;
},
async: false
});
if (!template || template.length === 0){
throw "NoTemplateError - Could not find template: '" + templateUrl + "'";
}
}
return template;
};
Marionette.TemplateCache.prototype.compileTemplate = function(rawTemplate) {
return Handlebars.compile(rawTemplate);
};
}(Handlebars, Marionette));
@chollier

This comment has been minimized.

Copy link

@chollier chollier commented Jun 21, 2013

Hi ! Thanks for sharing this piece of code :)

Could show an example of how to use then the template ?

@sashasimkin

This comment has been minimized.

Copy link

@sashasimkin sashasimkin commented Jun 27, 2013

@choiler There is my gist with one fix and small description which might help you
https://gist.github.com/sashasimkin/5876792

@hashchange

This comment has been minimized.

Copy link

@hashchange hashchange commented Jun 23, 2014

Thanks for this! I've been using it for a while. Marionette 2.0 has broken it, though. Marionette.$ is no longer with us, but replacing it with Backbone.$ does the job. I've just forked and fixed it, feel free to help yourself :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment