-
Notifications
You must be signed in to change notification settings - Fork 15
/
renderer.js
381 lines (331 loc) · 10.5 KB
/
renderer.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
// dependencies
var Cache = require("lru-cache");
var chalk = require("chalk");
var debug = require("debug")("koa-handlebars");
var extend = require("extend");
var fm = require("front-matter");
var fs = require("co-fs");
var handlebars = require("handlebars");
var path = require("path");
var thunkify = require("thunkify");
// helpers
var find = thunkify(require("find-alternate-file"));
var readdir = thunkify(require("recursive-readdir"));
// single export
module.exports = Renderer;
/**
* A Handlebars rendering abstraction class. Made a constructor to allow
* sub-classing and customization.
*
* @constructor
* @param {Object} options
*/
function Renderer(options) {
if (!(this instanceof Renderer)) {
return new Renderer(options);
}
// create complete options object (using defaults)
if (options) {
debug("creating koa-handlebars instance with options", options);
} else {
debug("creating koa-handlebars instance");
}
var o = this.options = extend({}, Renderer.defaults, options);
debug("using %s as the root", chalk.grey(o.root));
// custom handlebars instance
if (o.handlebars) {
debug("using a custom handlebars instance");
this.handlebars = o.handlebars;
} else {
this.handlebars = handlebars.create();
}
// register global helpers/partials
if (o.helpers) this.helper(o.helpers);
if (o.partials) this.partial(o.partials);
// enabling caching (via lru-cache)
if (o.cache) {
debug("caching enabled");
this.cache = new Cache({ max: 100 });
}
}
// reasonable defaults, exposed to allow users to change globally for their app
Renderer.defaults = require("./defaults.js");
/**
* Retrieves a file from the filesystem (and logs it)
*
* @param {String} file An absolute file path to a template file
* @returns {String}
*/
Renderer.prototype.getFile = function *(file) {
debug("reading file %s", chalk.grey(path.relative(this.options.root, file)));
return fm(yield fs.readFile(file, "utf8"));
};
/**
* Retrieves a file from disk and compiles it into a handlebars function
*
* @param {String} file An absolute path to a template file
* @returns {Function}
*/
Renderer.prototype.compileTemplate = function *(file) {
var meta = yield this.getFile(file);
debug("compiling template %s", chalk.grey(path.relative(this.options.root, file)));
meta.fn = this.handlebars.compile(meta.body);
meta.render = function (locals, options) {
return this.fn(locals, options);
};
return meta;
};
/**
* Retrieves a compiled template. Also gets/sets from the cache if enabled.
*
* @param {String} file An absolute path to a template file
* @returns {Function}
*/
Renderer.prototype.getTemplate = function *(file) {
var o = this.options;
var abs = yield find(file, o.extension);
if (!abs) throw new Error("Could not find template file: " + file);
var rel = path.relative(o.root, abs);
var key = "template:" + abs;
// when caching is enabled
if (o.cache) {
if (this.cache.peek(key)) { // check for existence
debug("template %s found in cache", chalk.grey(rel));
return this.cache.get(key);
} else {
var template = yield this.compileTemplate(abs);
debug("saving template %s to cache", chalk.grey(rel));
this.cache.set(key, template); // save to the cache
return template;
}
} else {
return yield this.compileTemplate(abs);
}
};
/**
* Generates an path to a view given it's "id", which is the value sent by the
* user in `this.render(":id")` in the koa app.
*
* If the path returned is relative, it will be assumed to be relative to the
* configured `viewsDir` (which is relative to the configured `root`)
*
* Example: "home" -> "views/home"
*
* @param {String} id
* @returns {String}
*/
Renderer.prototype.viewPath = function (id) {
var o = this.options;
var ret = o.viewPath.call(this, id);
if (path.isAbsolute(ret)) return ret;
return path.join(o.root, o.viewsDir, ret);
};
/**
* Retrieves the template for a view given it's "id"
*
* @param {String} id
* @returns {Function}
*/
Renderer.prototype.getView = function *(id) {
return yield this.getTemplate(this.viewPath(id));
};
/**
* Generates an absolute path to a layout given it's "id", which is the value
* sent by the user in `this.render("view", { layout: ":id" })` in the koa app.
* (or the value set in `options.defaultLayout`)
*
* Example: "main" -> "/path/to/root/layouts/main.hbs"
*
* @param {String} id
* @returns {String}
*/
Renderer.prototype.layoutPath = function (id) {
var o = this.options;
var ret = o.layoutPath.call(this, id);
if (path.isAbsolute(ret)) return ret;
return path.join(o.root, o.layoutsDir, ret);
};
/**
* Retrieves the template for a layout given it's "id"
*
* @param {String} id
* @returns {Function}
*/
Renderer.prototype.getLayout = function *(id) {
if (!id) return false;
return yield this.getTemplate(this.layoutPath(id));
};
/**
* Take the relative path (ie: `file`) and turn it into a handlebars-friendly
* partial name. (without slashes, file extension, etc)
*
* Example: ""
*
* @param {String} file Path to file, relative to partials dir
* @returns {String}
*/
Renderer.prototype.partialId = function (file) {
return this.options.partialId.call(this, file);
};
/**
* Finds the available partials in the partialsDir. If an array, it will loop
* and find all partials in the given dirs.
*
* @returns {Array:String} List of partial template filenames in all dirs
*/
Renderer.prototype.findPartials = function *() {
var o = this.options;
var dir = path.resolve(o.root, o.partialsDir);
var extensions = normalizeExtensions(o.extension);
var key = "partials:list:" + dir;
debug("searching for partials in %s", chalk.grey(dir));
var exists = yield fs.exists(dir);
if (!exists) return [];
if (o.cache && this.cache.peek(key)) return this.cache.get(key);
var files = yield readdir(dir);
files = files.map(function (file) {
return path.relative(dir, file);
});
files = files.filter(function (file) {
return extensions.indexOf(path.extname(file)) > -1;
});
if (o.cache) this.cache.set(key, files);
debug("%s partials found", chalk.green(files.length));
return files;
};
/**
* Retrieves a partial template from it's relative path
*
* @param {String} file
* @returns {Function}
*/
Renderer.prototype.getPartial = function *(file) {
var o = this.options;
var tpl = yield this.getTemplate(path.resolve(o.root, o.partialsDir, file));
return tpl.fn;
};
/**
* Returns all the compiled partials
*
* @returns {Object} Shallow hash of all partials
*/
Renderer.prototype.getPartials = function *() {
var self = this;
var files = yield this.findPartials();
return yield files.reduce(function (acc, file) {
acc[self.partialId(file)] = self.getPartial(file);
return acc;
}, {});
};
/**
* Registers one or more global partials with handlebars
* @see handlebars.registerPartial()
*
* @param {String} name
* @param {Function} fn
*/
Renderer.prototype.partial = function (name, fn) {
debug("registering global partial %s", chalk.underline(name));
this.handlebars.registerPartial(name, fn);
};
/**
* Registers one or more global helpers with handlebars
* @see handlebars.registerHelper()
*
* @param {String} name
* @param {Function} fn
*/
Renderer.prototype.helper = function (name, fn) {
debug("registering global helper %s", chalk.underline(name));
this.handlebars.registerHelper(name, fn);
};
/**
* The main workhorse function. Given the specified view (`template`)
* and `locals`, it will render and return. (with a layout if needed)
*
* `locals` has 1 special-case, which is `layout`. When specified, it will use
* the layout matching that "id" when rendering the view. (falling back to
* `options.defaultLayout` if specified)
*
* @param {String} template The view "id"
* @param {Object} [locals] The template params
* @param {Object} [options] Additional options for handlebars
*/
Renderer.prototype.render = function *(template, locals, options) {
var o = this.options;
locals = extend(true, {}, locals);
options = extend(true, {}, { data: o.data }, options);
debug("rendering %s template", chalk.underline(template));
// extract layout id
var layoutId = typeof locals.layout === 'undefined' ? o.defaultLayout : locals.layout;
delete locals.layout;
// extract pre-rendered body
var body = options.body;
// retrieve layout (if needed)
var layout = yield this.getLayout(layoutId);
// retrieve view
if (!body) var view = yield this.getView(template);
// extend locals with front-matter data
if (layout && layout.attributes) extend(locals, layout.attributes);
if (view && view.attributes) extend(locals, view.attributes);
// set up some special meta locals before rendering
options.data.view = template;
if (layoutId) options.data.layout = layoutId;
// load partials
options.partials = yield this.getPartials();
// when a layout is needed
if (layout) {
debug("rendering with layout %s", chalk.underline(layoutId));
options.data.body = body || view.render(locals, options);
return layout.render(locals, options);
} else {
return body || view.render(locals, options);
}
};
/**
* The main entry point for koa, this returns a middleware function that koa
* can use.
*
* @return {GeneratorFunction}
*/
Renderer.prototype.middleware = function () {
var self = this;
return function *(next) {
// renders the template and returns the string
// this allows you to do further processing on the response (like using
// another type besides HTML)
// this also merges in ctx.state and ctx.locals (if available)
this.renderView = function *(view, locals, options) {
var l = extend(true, {}, this.state, this.locals, locals);
var o = extend(true, { data: {} }, options);
o.data.koa = this;
try {
return yield self.render(view, l, o);
} catch (err) {
debug("unable to render view %s", chalk.underline(view), err.stack);
this.throw(500, "unable to render view: " + view + " because " + err.message);
}
};
// renders the template and automatically responds
this.render = function *(view, locals, options) {
this.type = "html";
this.body = yield this.renderView(view, locals, options);
};
yield next;
}
};
/**
* Normalize an array of file extensions:
*
* - Make an array if not already
* - Ensure each has the `.` prefix
*
* @param {Mixed} list
* @returns {Array:String}
*/
function normalizeExtensions(list) {
if (!Array.isArray(list)) list = [ list ];
return list.map(function (ext) {
return ext[0] === "." ? ext : "." + ext;
});
}