forked from tj/co-views
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (65 loc) · 1.64 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
/**
* Module dependencies.
*/
var debug = require('debug')('co-views');
var assign = require('object-assign');
var render = require('co-render');
var path = require('path');
var extname = path.extname;
var join = path.join;
/**
* Environment.
*/
var env = process.env.NODE_ENV || 'development';
/**
* Pass views `dir` and `opts` 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} [opts]
* @return {Function}
* @api public
*/
module.exports = function(dir, opts){
opts = opts || {};
debug('views %s %j', dir, opts);
// view directory
dir = dir || 'views';
// default extname
var ext = opts.ext || opts.default || 'html';
// engine map
var map = opts.map || {};
// proxy partials
var partials = opts.partials || {};
// cache compiled templates
var cache = opts.cache;
if (null == cache) cache = 'development' != env;
return function(view, locals){
locals = locals || {};
// merge opts.locals
if (opts.locals) {
locals = assign(locals, opts.locals);
}
// default extname
var e = extname(view);
if (!e) {
e = '.' + ext;
view += e;
}
// remove leading '.'
e = e.slice(1);
// map engine
locals.engine = map[e] || e;
// resolve
view = join(dir, view);
// cache
locals.cache = cache;
locals.partials = assign(locals.partials || {}, partials);
debug('render %s %j', view, locals);
return render(view, locals);
};
};