-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.js
452 lines (358 loc) · 10 KB
/
index.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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
'use strict';
const fs = require('fs');
const path = require('path');
const glob = require('glob');
const util = require('util');
/* Capture the layout name; thanks express-hbs */
const rLayoutPattern = /{{!<\s+([A-Za-z0-9\._\-\/]+)\s*}}/;
/**
* Shallow copy two objects into a new object
*
* Objects are merged from left to right. Thus, properties in objects further
* to the right are preferred over those on the left.
*
* @param {object} obj1
* @param {object} obj2
* @returns {object}
* @api private
*/
function merge (obj1, obj2) {
var c = {},
keys = Object.keys(obj2),
i;
for (i = 0; i !== keys.length; i++) {
c[keys[i]] = obj2[keys[i]];
}
keys = Object.keys(obj1);
for (i = 0; i !== keys.length; i++) {
if (!c.hasOwnProperty(keys[i])) {
c[keys[i]] = obj1[keys[i]];
}
}
return c;
};
/**
* file reader returning a thunk
* @param filename {String} Name of file to read
*/
function read (filename) {
return function (done) {
fs.readFile(filename, {encoding: 'utf8'}, done);
};
};
/**
* @class MissingTemplateError
* @param {String} message The error message
* @param {Object} extra The value of the template, relating to the error.
*/
function MissingTemplateError (message, extra) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.extra = extra;
};
util.inherits(MissingTemplateError, Error);
/**
* @class BadOptionsError
* @param {String} message The error message
* @param {Object} extra Misc infomration.
*/
function BadOptionsError (message, extra) {
Error.captureStackTrace(this, this.constructor);
this.name = this.constructor.name;
this.message = message;
this.extra = extra;
};
util.inherits(BadOptionsError, Error);
/**
* expose default instance of `Hbs`
*/
exports = module.exports = new Hbs();
/**
* expose method to create additional instances of `Hbs`
*/
exports.create = function () {
return new Hbs();
};
/**
* Create new instance of `Hbs`
*
* @api public
*/
function Hbs () {
if (!(this instanceof Hbs)) {
return new Hbs();
}
this.handlebars = require('handlebars').create();
this.Utils = this.handlebars.Utils;
this.SafeString = this.handlebars.SafeString;
}
/**
* Configure the instance.
*
* @api private
*/
Hbs.prototype.configure = function (options) {
var self = this;
if (!options.viewPath) {
throw new BadOptionsError('The option `viewPath` must be specified.');
}
// Attach options
options = options || {};
this.viewPath = options.viewPath;
this.handlebars = options.handlebars || this.handlebars;
this.templateOptions = options.templateOptions || {};
this.extname = options.extname || '.hbs';
this.partialsPath = options.partialsPath || [];
this.contentHelperName = options.contentHelperName || 'contentFor';
this.blockHelperName = options.blockHelperName || 'block';
this.defaultLayout = options.defaultLayout || '';
this.layoutsPath = options.layoutsPath || '';
this.locals = options.locals || {};
this.disableCache = options.disableCache || false;
this.partialsRegistered = false;
if (!Array.isArray(this.viewPath)) {
this.viewPath = [this.viewPath];
}
// Cache templates and layouts
this.cache = {};
this.blocks = {};
// block helper
this.registerHelper(this.blockHelperName, function (name, options) {
// instead of returning self.block(name), render the default content if no
// block is given
let val = self.block(name);
if (val === '' && typeof options.fn === 'function') {
val = options.fn(this);
}
return val;
});
// contentFor helper
this.registerHelper(this.contentHelperName, function (name, options) {
return self.content(name, options, this);
});
return this;
};
/**
* Middleware for koa
*
* @api public
*/
Hbs.prototype.middleware = function (options) {
this.configure(options);
let render = this.createRenderer();
return function *(next) {
this.render = render;
yield* next;
};
};
/**
* Create a render generator to be attached to koa context
*/
Hbs.prototype.createRenderer = function () {
let hbs = this;
return function *(tpl, locals) {
let tplPath = hbs.getTemplatePath(tpl),
template, rawTemplate, layoutTemplate;
if (!tplPath) {
throw new MissingTemplateError('The template specified does not exist.', tplPath);
}
// allow absolute paths to be used
if (path.isAbsolute(tpl)) {
tplPath = tpl + hbs.extname;
}
locals = merge(this.state || {}, locals || {});
locals = merge(hbs.locals, locals);
// Initialization... move these actions into another function to remove
// unnecessary checks
if (hbs.disableCache || !hbs.partialsRegistered && hbs.partialsPath !== '') {
yield hbs.registerPartials();
}
// Load the template
if (hbs.disableCache || !hbs.cache[tpl]) {
rawTemplate = yield read(tplPath);
hbs.cache[tpl] = {
template: hbs.handlebars.compile(rawTemplate)
};
// Load layout if specified
if (typeof locals.layout !== 'undefined' || rLayoutPattern.test(rawTemplate)) {
let layout = locals.layout;
if (typeof layout === 'undefined') {
layout = rLayoutPattern.exec(rawTemplate)[1];
}
if (layout !== false) {
let rawLayout = yield hbs.loadLayoutFile(layout);
hbs.cache[tpl].layoutTemplate = hbs.handlebars.compile(rawLayout);
}
else {
hbs.cache[tpl].layoutTemplate = hbs.handlebars.compile('{{{body}}}');
}
}
}
template = hbs.cache[tpl].template;
layoutTemplate = hbs.cache[tpl].layoutTemplate;
if (!layoutTemplate) {
layoutTemplate = yield hbs.getLayoutTemplate();
}
// Add the current koa context to templateOptions.data to provide access
// to the request within helpers.
if (!hbs.templateOptions.data) {
hbs.templateOptions.data = {};
}
hbs.templateOptions.data = merge(hbs.templateOptions.data, { koa: this });
// Run the compiled templates
locals.body = template(locals, hbs.templateOptions);
this.body = layoutTemplate(locals, hbs.templateOptions);
};
};
/**
* Get layout path
*/
Hbs.prototype.getLayoutPath = function (layout) {
if (this.layoutsPath) {
return path.join(this.layoutsPath, layout + this.extname);
}
return path.join(this.viewPath[0], layout + this.extname);
};
/**
* Lazy load default layout in cache.
*/
Hbs.prototype.getLayoutTemplate = function* () {
if (this.disableCache || !this.layoutTemplate) {
this.layoutTemplate = yield this.cacheLayout();
}
return this.layoutTemplate;
};
/**
* Get a default layout. If none is provided, make a noop
*/
Hbs.prototype.cacheLayout = function (layout) {
let hbs = this;
return function* () {
// Create a default layout to always use
if (!layout && !hbs.defaultLayout) {
return hbs.handlebars.compile('{{{body}}}');
}
// Compile the default layout if one not passed
if (!layout) {
layout = hbs.defaultLayout;
}
let layoutTemplate;
try {
let rawLayout = yield hbs.loadLayoutFile(layout);
layoutTemplate = hbs.handlebars.compile(rawLayout);
}
catch (err) {
console.error(err.stack);
}
return layoutTemplate;
};
};
/**
* Load a layout file
*/
Hbs.prototype.loadLayoutFile = function (layout) {
let hbs = this;
return function (done) {
let file = hbs.getLayoutPath(layout);
read(file)(done);
};
};
/**
* Register helper to internal handlebars instance
*/
Hbs.prototype.registerHelper = function () {
this.handlebars.registerHelper.apply(this.handlebars, arguments);
};
/**
* Register partial with internal handlebars instance
*/
Hbs.prototype.registerPartial = function () {
this.handlebars.registerPartial.apply(this.handlebars, arguments);
};
/**
* Register directory of partials
*/
Hbs.prototype.registerPartials = function () {
let self = this;
if (!Array.isArray(this.partialsPath)) {
this.partialsPath = [this.partialsPath];
}
/* thunk creator for readdirp */
var readdir = function (root) {
return function (done) {
glob('**/*' + self.extname, {
cwd: root,
}, done);
};
};
/* Read in partials and register them */
return function* () {
try {
let resultList = yield self.partialsPath.map(readdir),
files = [],
names = [],
partials,
i;
if (!resultList.length) {
return;
}
// Generate list of files and template names
resultList.forEach((result, i) => {
result.forEach((file) => {
files.push(path.join(self.partialsPath[i], file));
names.push(file.slice(0, -1 * self.extname.length));
});
});
// Read all the partial from disk
partials = yield files.map(read);
for (i = 0; i !== partials.length; i++) {
self.registerPartial(names[i], partials[i]);
}
self.partialsRegistered = true;
}
catch (e) {
console.error('Error caught while registering partials');
console.error(e);
}
};
};
Hbs.prototype.getTemplatePath = function (tpl) {
let cache = (this.pathCache || (this.pathCache = {})),
i;
if (cache[tpl])
return cache[tpl];
for (i = 0; i !== this.viewPath.length; i++) {
let viewPath = this.viewPath[i],
tplPath = path.join(viewPath, tpl + this.extname);
try {
fs.statSync(tplPath);
if (!this.disableCache)
cache[tpl] = tplPath;
return tplPath;
}
catch (e) {
continue;
}
}
return void 0;
};
/**
* The contentFor helper delegates to here to populate block content
*/
Hbs.prototype.content = function (name, options, context) {
// fetch block
let block = this.blocks[name] || (this.blocks[name] = []);
// render block and save for layout render
block.push(options.fn(context));
};
/**
* block helper delegates to this function to retreive content
*/
Hbs.prototype.block = function (name) {
// val = block.toString
let val = (this.blocks[name] || []).join('\n');
// clear the block
this.blocks[name] = [];
return val;
};