-
Notifications
You must be signed in to change notification settings - Fork 383
/
express-handlebars.js
340 lines (274 loc) · 10.2 KB
/
express-handlebars.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/*
* Copyright (c) 2015, Yahoo Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
'use strict';
var Promise = global.Promise || require('promise');
var glob = require('glob');
var Handlebars = require('handlebars');
var fs = require('graceful-fs');
var path = require('path');
var utils = require('./utils');
module.exports = ExpressHandlebars;
// -----------------------------------------------------------------------------
function ExpressHandlebars(config) {
// Config properties with defaults.
utils.assign(this, {
handlebars : Handlebars,
extname : '.handlebars',
layoutsDir : 'views/layouts/',
partialsDir : 'views/partials/',
defaultLayout : undefined,
helpers : null,
compilerOptions: null,
}, config);
// Express view engine integration point.
this.engine = this.renderView.bind(this);
// Normalize `extname`.
if (this.extname.charAt(0) !== '.') {
this.extname = '.' + this.extname;
}
// Internal caches of compiled and precompiled templates.
this.compiled = Object.create(null);
this.precompiled = Object.create(null);
// Private internal file system cache.
this._fsCache = Object.create(null);
}
ExpressHandlebars.prototype.getPartials = function (options) {
var partialsDirs = Array.isArray(this.partialsDir) ?
this.partialsDir : [this.partialsDir];
partialsDirs = partialsDirs.map(function (dir) {
var dirPath;
var dirTemplates;
var dirNamespace;
// Support `partialsDir` collection with object entries that contain a
// templates promise and a namespace.
if (typeof dir === 'string') {
dirPath = dir;
} else if (typeof dir === 'object') {
dirTemplates = dir.templates;
dirNamespace = dir.namespace;
dirPath = dir.dir;
}
// We must have some path to templates, or templates themselves.
if (!(dirPath || dirTemplates)) {
throw new Error('A partials dir must be a string or config object');
}
// Make sure we're have a promise for the templates.
var templatesPromise = dirTemplates ? Promise.resolve(dirTemplates) :
this.getTemplates(dirPath, options);
return templatesPromise.then(function (templates) {
return {
templates: templates,
namespace: dirNamespace,
};
});
}, this);
return Promise.all(partialsDirs).then(function (dirs) {
var getTemplateName = this._getTemplateName.bind(this);
return dirs.reduce(function (partials, dir) {
var templates = dir.templates;
var namespace = dir.namespace;
var filePaths = Object.keys(templates);
filePaths.forEach(function (filePath) {
var partialName = getTemplateName(filePath, namespace);
partials[partialName] = templates[filePath];
});
return partials;
}, {});
}.bind(this));
};
ExpressHandlebars.prototype.getTemplate = function (filePath, options) {
filePath = path.resolve(filePath);
options || (options = {});
var precompiled = options.precompiled;
var cache = precompiled ? this.precompiled : this.compiled;
var template = options.cache && cache[filePath];
if (template) {
return template;
}
// Optimistically cache template promise to reduce file system I/O, but
// remove from cache if there was a problem.
template = cache[filePath] = this._getFile(filePath, {cache: options.cache})
.then(function (file) {
if (precompiled) {
return this._precompileTemplate(file, this.compilerOptions);
}
return this._compileTemplate(file, this.compilerOptions);
}.bind(this));
return template.catch(function (err) {
delete cache[filePath];
throw err;
});
};
ExpressHandlebars.prototype.getTemplates = function (dirPath, options) {
options || (options = {});
var cache = options.cache;
return this._getDir(dirPath, {cache: cache}).then(function (filePaths) {
var templates = filePaths.map(function (filePath) {
return this.getTemplate(path.join(dirPath, filePath), options);
}, this);
return Promise.all(templates).then(function (templates) {
return filePaths.reduce(function (hash, filePath, i) {
hash[filePath] = templates[i];
return hash;
}, {});
});
}.bind(this));
};
ExpressHandlebars.prototype.render = function (filePath, context, options) {
options || (options = {});
return Promise.all([
this.getTemplate(filePath, {cache: options.cache}),
options.partials || this.getPartials({cache: options.cache}),
]).then(function (templates) {
var template = templates[0];
var partials = templates[1];
var helpers = options.helpers || this.helpers;
// Add ExpressHandlebars metadata to the data channel so that it's
// accessible within the templates and helpers, namespaced under:
// `@exphbs.*`
var data = utils.assign({}, options.data, {
exphbs: utils.assign({}, options, {
filePath: filePath,
helpers : helpers,
partials: partials,
}),
});
return this._renderTemplate(template, context, {
data : data,
helpers : helpers,
partials: partials,
});
}.bind(this));
};
ExpressHandlebars.prototype.renderView = function (viewPath, options, callback) {
options || (options = {});
var context = options;
// Express provides `settings.views` which is the path to the views dir that
// the developer set on the Express app. When this value exists, it's used
// to compute the view's name.
var view;
var viewsPath = options.settings && options.settings.views;
if (viewsPath) {
view = this._getTemplateName(path.relative(viewsPath, viewPath));
}
// Merge render-level and instance-level helpers together.
var helpers = utils.assign({}, this.helpers, options.helpers);
// Merge render-level and instance-level partials together.
var partials = Promise.all([
this.getPartials({cache: options.cache}),
Promise.resolve(options.partials),
]).then(function (partials) {
return utils.assign.apply(null, [{}].concat(partials));
});
// Pluck-out ExpressHandlebars-specific options and Handlebars-specific
// rendering options.
options = {
cache : options.cache,
view : view,
layout: 'layout' in options ? options.layout : this.defaultLayout,
data : options.data,
helpers : helpers,
partials: partials,
};
this.render(viewPath, context, options)
.then(function (body) {
var layoutPath = this._resolveLayoutPath(options.layout);
if (layoutPath) {
return this.render(
layoutPath,
utils.assign({}, context, {body: body}),
utils.assign({}, options, {layout: undefined})
);
}
return body;
}.bind(this))
.then(utils.passValue(callback))
.catch(utils.passError(callback));
};
// -- Protected Hooks ----------------------------------------------------------
ExpressHandlebars.prototype._compileTemplate = function (template, options) {
return this.handlebars.compile(template, options);
};
ExpressHandlebars.prototype._precompileTemplate = function (template, options) {
return this.handlebars.precompile(template, options);
};
ExpressHandlebars.prototype._renderTemplate = function (template, context, options) {
return template(context, options);
};
// -- Private ------------------------------------------------------------------
ExpressHandlebars.prototype._getDir = function (dirPath, options) {
dirPath = path.resolve(dirPath);
options || (options = {});
var cache = this._fsCache;
var dir = options.cache && cache[dirPath];
if (dir) {
return dir.then(function (dir) {
return dir.concat();
});
}
var pattern = '**/*' + this.extname;
// Optimistically cache dir promise to reduce file system I/O, but remove
// from cache if there was a problem.
dir = cache[dirPath] = new Promise(function (resolve, reject) {
glob(pattern, {
cwd : dirPath,
follow: true
}, function (err, dir) {
if (err) {
reject(err);
} else {
resolve(dir);
}
});
});
return dir.then(function (dir) {
return dir.concat();
}).catch(function (err) {
delete cache[dirPath];
throw err;
});
};
ExpressHandlebars.prototype._getFile = function (filePath, options) {
filePath = path.resolve(filePath);
options || (options = {});
var cache = this._fsCache;
var file = options.cache && cache[filePath];
if (file) {
return file;
}
// Optimistically cache file promise to reduce file system I/O, but remove
// from cache if there was a problem.
file = cache[filePath] = new Promise(function (resolve, reject) {
fs.readFile(filePath, 'utf8', function (err, file) {
if (err) {
reject(err);
} else {
resolve(file);
}
});
});
return file.catch(function (err) {
delete cache[filePath];
throw err;
});
};
ExpressHandlebars.prototype._getTemplateName = function (filePath, namespace) {
var extRegex = new RegExp(this.extname + '$');
var name = filePath.replace(extRegex, '');
if (namespace) {
name = namespace + '/' + name;
}
return name;
};
ExpressHandlebars.prototype._resolveLayoutPath = function (layoutPath) {
if (!layoutPath) {
return null;
}
if (!path.extname(layoutPath)) {
layoutPath += this.extname;
}
return path.resolve(this.layoutsDir, layoutPath);
};