forked from hurrymaplelad/rendr-handlebars
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathtemplateFinder.js
63 lines (53 loc) · 1.79 KB
/
templateFinder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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
}
};