forked from publicclass/express-partials
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
367 lines (318 loc) · 9.44 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
var path = require('path')
, fs = require('fs')
, exists = fs.existsSync || path.existsSync
, resolve = path.resolve
, dirname = path.dirname
, extname = path.extname
, basename = path.basename;
/**
* Express 3.x Layout & Partial support.
*
* The beloved feature from Express 2.x is back as a middleware.
*
* Example:
*
* var express = require('express')
* , partials = require('express-partials')
* , app = express();
* app.use(partials());
* // three ways to register a template engine:
* partials.register('coffee','coffeekup');
* partials.register('coffee',require('coffeekup'));
* partials.register('coffee',require('coffeekup').render);
* app.get('/',function(req,res,next){
* res.render('index.ejs') // renders layout.ejs with index.ejs as `body`.
* })
*
* Options:
*
* none
*
*/
module.exports = function(){
return function(req,res,next){
// res.partial(view,options) -> res.render() (ignores any layouts)
res.partial = res.render;
// in template partial(view,options)
res.locals.partial = partial.bind(res);
// layout support
var _render = res.render.bind(res);
res.render = function(name, options, fn){
var layout = options && options.layout;
// default layout
if( layout === true || layout === undefined ) {
// Try to find default layout in view options, if not found, seek for 'layout'
var viewOptions = res.app.get('view options');
layout = viewOptions && viewOptions.defaultLayout || 'layout';
}
// layout
if( layout ){
// first render normally
_render(name, options, function(err, body){
if( err )
return fn ? fn(err) : req.next(err);
options = options || {};
options.body = body;
// calculate the layout vars
var ext = extname(name) || '.'+(res.app.get('view engine') || 'ejs');
var root = req.app.get('views') || process.cwd() + '/views';
var dir = dirname(layout) == '.' ? root : resolve(root,dirname(layout));
var filename = dir+(path.sep||'/')+basename(layout,ext)+ext;
// See if we even have a layout to use
// If so, render it. If not, then fallback to just the original template
if (exists(filename)) {
layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext;
_render(layout, options, fn);
} else {
// layout may be in the same folder than the view
dir = dirname(name) == '.' ? root : resolve(root,dirname(name));
filename = dir+(path.sep||'/')+basename(layout,ext)+ext;
if(exists(filename)) {
layout = dirname(lookup(dir, layout, ext))+(path.sep||'/')+basename(layout,ext)+ext;
_render(layout, options, fn);
} else {
_render(name, options, fn);
}
}
})
// no layout
} else {
_render(name, options, fn);
}
}
// done
next();
}
}
/***
* Allow to register a specific rendering
* function for a given extension.
* (Similar to Express 2.x register() function.)
*
* The second argument might be:
* a template module's name
* a module with a `render` method
* a synchronous `render` method
*/
function register(ext,render){
if(ext[0] != '.') {
ext = '.' + ext;
}
if(typeof render == 'string') {
render = require(render);
}
if(typeof render.render != 'undefined') {
register[ext] = render.render;
} else {
register[ext] = render;
}
};
module.exports.register = register;
/**
* Automatically assign a render() function
* from a module of the same name if none
* has been registered.
*/
function renderer(ext){
if(ext[0] !== '.'){
ext = '.' + ext;
}
return register[ext] != null
? register[ext]
: register[ext] = require(ext.slice(1)).render;
};
module.exports.renderer = renderer;
/**
* Memory cache for resolved object names.
*/
var cache = {};
/**
* Resolve partial object name from the view path.
*
* Examples:
*
* "user.ejs" becomes "user"
* "forum thread.ejs" becomes "forumThread"
* "forum/thread/post.ejs" becomes "post"
* "blog-post.ejs" becomes "blogPost"
*
* @return {String}
* @api private
*/
function resolveObjectName(view){
return cache[view] || (cache[view] = view
.split(path.sep || '/')
.slice(-1)[0]
.split('.')[0]
.replace(/^_/, '')
.replace(/[^a-zA-Z0-9 ]+/g, ' ')
.split(/ +/).map(function(word, i){
return i
? word[0].toUpperCase() + word.substr(1)
: word;
}).join(''));
};
/**
* Lookup:
*
* - partial `_<name>`
* - any `<name>/index`
* - non-layout `../<name>/index`
* - any `<root>/<name>`
* - partial `<root>/_<name>`
*
* @param {View} view
* @return {String}
* @api private
*/
function lookup(root, view, ext){
var name = resolveObjectName(view);
var original = view;
// Try root ex: <root>/user.jade
view = resolve(root, basename(original,ext)+ext);
if( exists(view) ) return view;
// Try subdir ex: <root>/subdir/user.jade
view = resolve(root, dirname(original), basename(original,ext)+ext);
if( exists(view) ) return view;
// Try _ prefix ex: ./views/_<name>.jade
// taking precedence over the direct path
view = resolve(root,'_'+name+ext)
if( exists(view) ) return view;
// Try index ex: ./views/user/index.jade
view = resolve(root,name,'index'+ext);
if( exists(view) ) return view;
// Try ../<name>/index ex: ../user/index.jade
// when calling partial('user') within the same dir
view = resolve(root,'..',name,'index'+ext);
if( exists(view) ) return view;
// Try root ex: <root>/user.jade
view = resolve(root,name+ext);
if( exists(view) ) return view;
return null;
};
module.exports.lookup = lookup;
/**
* Render `view` partial with the given `options`. Optionally a
* callback `fn(err, str)` may be passed instead of writing to
* the socket.
*
* Options:
*
* - `object` Single object with name derived from the view (unless `as` is present)
*
* - `as` Variable name for each `collection` value, defaults to the view name.
* * as: 'something' will add the `something` local variable
* * as: this will use the collection value as the template context
* * as: global will merge the collection value's properties with `locals`
*
* - `collection` Array of objects, the name is derived from the view name itself.
* For example _video.html_ will have a object _video_ available to it.
*
* @param {String} view
* @param {Object|Array} options, collection or object
* @return {String}
* @api public
*/
function partial(view, options){
var collection
, object
, locals
, name;
// parse options
if( options ){
// collection
if( options.collection ){
collection = options.collection;
delete options.collection;
} else if( 'length' in options ){
collection = options;
options = {};
}
// locals
if( options.locals ){
locals = options.locals;
delete options.locals;
}
// object
if( 'Object' != options.constructor.name ){
object = options;
options = {};
} else if( options.object != undefined ){
object = options.object;
delete options.object;
}
} else {
options = {};
}
// merge locals into options
if( locals )
options.__proto__ = locals;
// merge app locals into
for(var k in this.app.locals)
options[k] = options[k] || this.app.locals[k];
// merge locals, which as set using app.use(function(...){ res.locals = X; })
for(var k in this.req.res.locals)
options[k] = options[k] || this.req.res.locals[k];
// let partials render partials
options.partial = partial.bind(this);
// extract object name from view
name = options.as || resolveObjectName(view);
// find view
var root = this.app.get('views') || process.cwd() + '/views'
, ext = extname(view) || '.' + (this.app.get('view engine')||'ejs')
, file = lookup(root, view, ext);
// read view
var source = fs.readFileSync(file,'utf8');
// set filename option for renderer (Jade requires this for includes)
options.filename = file;
// render partial
function render(){
if (object) {
if ('string' == typeof name) {
options[name] = object;
} else if (name === global) {
// wtf?
// merge(options, object);
}
}
options.locals = locals
return renderer(ext)(source, options);
}
// Collection support
if (collection) {
var len = collection.length
, buf = ''
, keys
, key
, val;
if ('number' == typeof len || Array.isArray(collection)) {
options.collectionLength = len;
for (var i = 0; i < len; ++i) {
val = collection[i];
options.firstInCollection = i == 0;
options.indexInCollection = i;
options.lastInCollection = i == len - 1;
object = val;
buf += render();
}
} else {
keys = Object.keys(collection);
len = keys.length;
options.collectionLength = len;
options.collectionKeys = keys;
for (var i = 0; i < len; ++i) {
key = keys[i];
val = collection[key];
options.keyInCollection = key;
options.firstInCollection = i == 0;
options.indexInCollection = i;
options.lastInCollection = i == len - 1;
object = val;
buf += render();
}
}
return buf;
} else {
return render();
}
}