/
doT.js
58 lines (51 loc) · 1.82 KB
/
doT.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
// doT.js
// (c) 2011, Laura Doktorova
// https://github.com/olado/doT
//
// doT is an extraction and slight modification of an excellent
// templating function from jQote2.js (jQuery plugin) by aefxx
// (http://aefxx.com/jquery-plugins/jqote2/).
//
// Modifications:
// 1. nodejs support
// 2. allow for custom template markers
// 3. only allow direct invocation of the compiled function
//
// Licensed under the MIT license.
(function() {
var doT = { version : '0.1.0' };
if (typeof module !== 'undefined' && module.exports) {
module.exports = doT;
} else {
this.doT = doT;
}
doT.templateSettings = {
begin : '{{',
end : '}}',
varname : 'it'
};
doT.template = function(tmpl, conf) {
conf = conf || doT.templateSettings;
var str = '', tb = conf.begin, te = conf.end, m, l,
arr = tmpl.replace(/\s*<!\[CDATA\[\s*|\s*\]\]>\s*|[\r\n\t]|(\/\*[\s\S]*?\*\/)/g, '')
.split(tb).join(te +'\x1b')
.split(te);
for (m=0,l=arr.length; m < l; m++) {
str += arr[m].charAt(0) !== '\x1b' ?
"out+='" + arr[m].replace(/(\\|["'])/g, '\\$1') + "'" : (arr[m].charAt(1) === '=' ?
';out+=(' + arr[m].substr(2) + ');' : (arr[m].charAt(1) === '!' ?
';out+=(' + arr[m].substr(2) + ").toString().replace(/&(?!\\w+;)/g, '&').split('<').join('<').split('>').join('>').split('" + '"' + "').join('"').split(" + '"' + "'" + '"' + ").join(''');" : ';' + arr[m].substr(1)));
}
str = 'try{' +
('var out="";'+str+';return out;')
.split("out+='';").join('')
.split('var out="";out+=').join('var out=') +
'} catch(e){e.type="TemplateExecutionError";e.args=arguments;e.template=arguments.callee.toString();throw e;}';
try {
return new Function(conf.varname, str);
} catch (e) {
if (typeof console !== 'undefined') console.log("Could not create a template function: " + str);
throw e;
}
};
}());