-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
118 lines (93 loc) · 2.33 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
'use strict';
/**
* Dependencies
*/
var debug = require('debug')('koan-views');
var render = require('co-render');
var path = require('path');
var co = require('co');
/**
* Environment
*/
var env = process.env.NODE_ENV || 'development';
/**
* Pass views `dir` and `options` to return
* a render function.
*
* - `map` an object mapping extnames to engine names [{}]
* - `default` default extname to use when missing [html]
* - `cache` cached compiled functions [NODE_ENV != 'development']
*
* @param {String} [dir]
* @param {Object} [options]
* @return {Function}
* @api public
*/
module.exports = function(dir, options) {
options = options || {};
debug('views %s %j', dir, options);
// View directory
dir = dir || 'views';
// Default extname
var ext = options.ext || options.default || 'html';
// Engine map
var map = options.map || {};
// Cache compiled templates
var cache = options.cache;
if (null == cache)
cache = 'development' != env;
// Default layout
var defaultLayout = options.defaultLayout;
return function(view, locals, layout) {
locals = locals || {};
layout = layout || defaultLayout;
// Make `locals` optional
if ((typeof locals == 'string')||(locals instanceof String)) {
layout = locals;
locals = {};
}
// Default extname
var e = path.extname(view);
if (!e) {
e = '.' + ext;
view += e;
if (layout)
layout += e;
}
// Remove leading '.'
e = e.slice(1);
// Map engine
locals.engine = map[e] || e;
// Cache
locals.cache = cache;
// Resolve view
view = path.join(dir, view);
var renderBody;
if (layout) {
debug('render %s %j', view, locals);
// Yielded view rendering
renderBody = co(function*() {
debug('render %s %j', view, locals);
var body = yield render(view, locals);
return body;
});
// Resolve layout
layout = path.join(dir, layout);
}
else
layout = view;
return function(done) {
if (renderBody) {
renderBody(function(err, body) {
if (err)
return done(err);
locals.body = body;
debug('render %s %j', layout, locals);
render(layout, locals)(done);
});
}
else
render(layout, locals)(done);
}
};
};