-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtpl_jquery.js
More file actions
107 lines (89 loc) · 2.71 KB
/
tpl_jquery.js
File metadata and controls
107 lines (89 loc) · 2.71 KB
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
// Based on http://ejohn.org/blog/javascript-micro-templating/
// Free permission to use granted under BSD licence
// name : string, REQUIRE, DOM element ID with TPL text & tpl name in storage
// url : string, if need load tpl text from url
// data : mixed, default={}, for TPL data
// done : function, when tpl will inserted
// pos : string, default=down, top | down, for only tpl_append
(function($) {
var Cache = {};
$.fn.tpl_insert = function(param)
{
applyTpl(param, this, 'insert');
return this;
};
$.fn.tpl_append = function(param)
{
applyTpl(param, this, 'append');
return this;
};
function applyTpl(param, context_element, type)
{
tpl_text = '';
if ('name' in param)
{
if (param.name in Cache)
{
tpl_text = Cache[param.name];
}
else if ('url' in param)
{
var ajax_param = {};
if ('url_param' in param)
{
ajax_param.data = param.url_param;
}
ajax_param.url = param.url;
ajax_param.dataType = 'html';
ajax_param.success = function(data, textStatus, jqXHR)
{
Cache[param.name] = data;
param.url = null;
applyTpl(param, context_element, type);
};
$.ajax(ajax_param);
return;
}
else
{
Cache[param.name] = $('#'+param.name).html();
tpl_text = Cache[param.name];
}
param.data = ('data' in param?param.data:{});
if (type == 'append')
{
if ('pos' in param && param.pos == 'top')
{
context_element.append(getGeneratedText(tpl_text, param.data));
}
else
{
context_element.prepend(getGeneratedText(tpl_text, param.data));
}
}
else
{
context_element.html(getGeneratedText(tpl_text, param.data));
}
if ('done' in param && typeof(param.done) == 'function')
{
param.done(context_element);
}
}
}
function getGeneratedText(tpl_text, data)
{
var fn_text = "var p=[];data=obj;p.push('" +
tpl_text.trim()
.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('');";
var fn = new Function('obj', fn_text);
return fn(data);
}
})(jQuery);