forked from caolan/nodeunit
/
ejs.js
125 lines (108 loc) · 2.54 KB
/
ejs.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
/*!
* EJS
* Copyright(c) 2010 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var sys = require('sys');
/**
* Library version.
*/
exports.version = '0.0.3';
/**
* Intermediate js cache.
*
* @type Object
*/
var cache = {};
/**
* Clear intermediate js cache.
*
* @api public
*/
exports.clearCache = function(){
cache = {};
};
/**
* Escape the given string of `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
function escape(html){
return String(html)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
/**
* Parse the given `str` of ejs, returning the function body.
*
* @param {String} str
* @return {String}
* @api public
*/
var parse = exports.parse = function(str){
return 'var buf = [];\n'
+ "with (locals) {\nbuf.push('"
+ String(str)
.replace(/[\r\t]/g, " ")
.replace(/\n/g, "\\n")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "', escape($1) ,'")
.replace(/\t-(.*?)%>/g, "', $1 ,'")
.split("\t").join("');")
.split("%>").join("buf.push('")
.split("\r").join("\\'")
+ "');\n}\nreturn buf.join('');";
};
/**
* Compile the given `str` of ejs into a `Function`.
*
* @param {String} str
* @param {Object} options
* @return {Function}
* @api public
*/
var compile = exports.compile = function(str, options){
if (options.debug) sys.puts(parse(str));
return new Function('locals, escape', parse(str));
};
/**
* Render the given `str` of ejs.
*
* Options:
*
* - `locals` Local variables object
* - `cache` Compiled functions are cached, requires `filename`
* - `filename` Used by `cache` to key caches
* - `context|scope` Function execution context
* - `debug` Output generated function body
*
* @param {String} str
* @param {Object} options
* @return {String}
* @api public
*/
exports.render = function(str, options){
var fn,
options = options || {};
if (options.cache) {
if (options.filename) {
fn = cache[options.filename] = compile(str, options);
} else {
throw new Error('"cache" option requires "filename".');
}
} else {
fn = compile(str, options);
}
return fn.call(
options.context || options.scope,
options.locals || {},
escape);
};