forked from AndersSahlin/MailCheckerPlus
/
template-engine.js
51 lines (48 loc) · 2.07 KB
/
template-engine.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
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
var _tmplCache = {}
this.parseTemplate = function (str, data) {
/// <summary>
/// Client side template parser that uses <#= #> and <# code #> expressions.
/// and # # code blocks for template expansion.
/// NOTE: chokes on single quotes in the document in some situations
/// use &rsquo; for literals in text and avoid any single quote
/// attribute delimiters.
/// </summary>
/// <param name="str" type="string">The text of the template to expand</param>
/// <param name="data" type="var">
/// Any data that is to be merged. Pass an object and
/// that object's properties are visible as variables.
/// </param>
/// <returns type="string" />
var err = "";
try {
var func = _tmplCache[str];
if (!func) {
var strFunc =
"var p=[],print=function(){p.push.apply(p,arguments);};" +
"with(obj){p.push('" +
// str
// .replace(/[\r\t\n]/g, " ")
// .split("<#").join("\t")
// .replace(/((^|#>)[^\t]*)'/g, "$1\r")
// .replace(/\t=(.*?)#>/g, "',$1,'")
// .split("\t").join("');")
// .split("#>").join("p.push('")
// .split("\r").join("\\'") + "');}return p.join('');";
str.replace(/[\r\t\n]/g, " ")
.replace(/'(?=[^#]*#>)/g, "\t")
.split("'").join("\\'")
.split("\t").join("'")
.replace(/<#=(.+?)#>/g, "',$1,'")
.split("<#").join("');")
.split("#>").join("p.push('")
+ "');}return p.join('');";
//alert(strFunc);
func = new Function("obj", strFunc);
_tmplCache[str] = func;
}
return func(data);
} catch (e) { err = e.message; }
return "< # ERROR: " + err + " # >";
}