Skip to content

Instantly share code, notes, and snippets.

@hamishhossack
Created July 27, 2015 14:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamishhossack/7a138d224354ada0d81b to your computer and use it in GitHub Desktop.
Save hamishhossack/7a138d224354ada0d81b to your computer and use it in GitHub Desktop.
Override Marionette With Twig Templates (use cache templates)
var loadExistingTwigTemplate = function (templateId) {
return Twig.twig({
ref: templateId
});
};
Marionette.TemplateCache.prototype.compileTemplate = function (template) {
switch (template.type) {
case 'twig/template':
// first, see if the template is already loaded
var existingTemplate = loadExistingTwigTemplate(template.id);
if (!_.isUndefined(existingTemplate)) return existingTemplate;
var tpl;
try {
tpl = Twig.twig({
id: template.id,
data: template.html
});
} catch (e) {
tpl = Twig.twig({'ref': template.id});
}
return tpl;
default:
return _.template(template.html);
}
};
Marionette.TemplateCache.prototype.loadTemplate = function (templateId) {
// first, see if the template is already loaded
if (loadExistingTwigTemplate(templateId) !== null) {
return {
id: templateId,
type: 'twig/template'
};
}
// second, load the template from a script tag
// eg: <script type="twig/template" id="templateId">
var template = {
html: $(templateId).html(),
type: $(templateId).attr('type')
};
if (_.isUndefined(template.html) || _.isNull(template.html)) {
return console.debug("Could not find template: '" + templateId + "'", "NoTemplateError");
}
return template;
};
Marionette.Renderer = {
render: function (template, data) {
if (!template) {
throw new Marionette.Error({
name: 'TemplateNotFoundError',
message: 'Cannot render the template since its false, null or undefined.'
});
}
// If the template is a function call it with data
if (_.isFunction(template)) return template(data);
if (_.isFunction(template.render)) return template.render(data);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment