-
Notifications
You must be signed in to change notification settings - Fork 2
/
templates.js
68 lines (57 loc) · 1.56 KB
/
templates.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
64
65
66
67
68
/**
* Loads templates from 'templates' directory
* and compiles them with Handlebars returning
* an object keyed by the template filename.
*
* E.g server.action.subaction.format.xml will
* be returned as
* {
* server: {
* action: {
* subaction: {
* format: {
* xml
* }
* }
* }
* }
* }
*
* Where xml is a compiled Handlebars template
* function for server.action.subaction.format.xml
*
* Or to be more useful: task.create({taskId: id})
*
*/
'use strict';
var Handlebars = require('handlebars');
var fs = require('fs');
var path = require('path');
var templates = {};
//Templates are loaded from ./templates
var templateDir = path.join(__dirname, 'templates');
var templateNames = fs.readdirSync(templateDir);
templateNames.forEach(function (templateName) {
var template = fs.readFileSync(path.join(templateDir, templateName), 'utf8');
var compiledTemplate = Handlebars.compile(template);
var templateParts = templateName.split('.');
//Pointer to object / nested object in templates
var obj = templates;
//Loop over each . separated component
while (templateParts.length >= 1) {
var part = templateParts.shift();
if (templateParts.length === 0) {
//If this is the last part store the
//Handlebars compiled template in the
//property we last created
obj[part] = compiledTemplate;
} else {
//Ensure that an object exists for
//this property
obj[part] = obj[part] || {};
}
//Move pointer one property deeper
obj = obj[part];
}
});
module.exports = templates;