/
index.js
84 lines (69 loc) · 1.37 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
/**
* Expose `render()`.`
*/
exports = module.exports = render;
/**
* Expose `compile()`.
*/
exports.compile = compile;
/**
* Render the given mustache `str` with `obj`.
*
* @param {String} str
* @param {Object} obj
* @return {String}
* @api public
*/
function render(str, obj) {
obj = obj || {};
var fn = compile(str);
return fn(obj);
}
/**
* Compile the given `str` to a `Function`.
*
* @param {String} str
* @return {Function}
* @api public
*/
function compile(str) {
var js = [];
var toks = parse(str);
var tok;
for (var i = 0; i < toks.length; ++i) {
tok = toks[i];
if (i % 2 == 0) {
js.push('"' + tok.replace(/"/g, '\\"') + '"');
} else {
if (!tok.match(/^[\w.]+$/)) throw new Error('invalid property "' + tok + '"');
js.push(' + escape(obj.' + tok + ') + ');
}
}
js = js.join('').replace(/\n/g, '\\n');
js = escape.toString().replace(/^/gm, ' ') + ';\n return ' + js;
return new Function('obj', js);
}
/**
* Parse `str`.
*
* @param {String} str
* @return {Array}
* @api private
*/
function parse(str) {
return str.split(/\{\{|\}\}/);
}
/**
* Escape the given `html`.
*
* @param {String} html
* @return {String}
* @api private
*/
function escape(html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
}