UNPKG

rendr-handlebars

Version:

Glue handlebars templates into a Rendr app.

64 lines (53 loc) 1.83 kB
var cachedTemplates = {}; module.exports = function(Handlebars) { /** * Provide a way for apps to specify that different template name patterns * should use different compiled template files. * */ var templatePatterns = []; /** * Given a template name, return the compiled Handlebars template. */ function getTemplate(templateName) { /** * Find the correct source file for this template. */ var src = getSrcForTemplate(templateName); /** * Allow compiledTemplates to be created asynchronously by lazy-requiring it. */ if (!cachedTemplates[src]) { cachedTemplates[src] = require(src); /** * Make it play nicely with both AMD and CommonJS. * The `grunt-contrib-handlebars` module produces different stucture * of compiled templates with `amd` vs `commonjs` options. Accommodate * both options here. the `amd` option results in templates as an Object, * whereas the `commonjs` option results in templates as a Function. */ if (typeof cachedTemplates[src] == 'function') { cachedTemplates[src] = cachedTemplates[src](Handlebars); } } return cachedTemplates[src][templateName]; } /** * For a given template name, find the correct compiled templates source file * based on pattern matching on the template name. */ function getSrcForTemplate(templateName) { var currentPattern = templatePatterns.filter(function(obj) { return obj.pattern.test(templateName); })[0]; if (currentPattern == null) { throw new Error('No pattern found to match template "' + templateName + '".'); } return currentPattern.src; } return { getTemplate: getTemplate, getSrcForTemplate: getSrcForTemplate, templatePatterns: templatePatterns } };