forked from goofychris/art-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
template-extensions.js
133 lines (96 loc) · 2.71 KB
/
template-extensions.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
126
127
128
129
130
131
132
133
/*!
* artTemplate - Syntax Extensions
* https://github.com/aui/artTemplate
* Released under the MIT, BSD, and GPL Licenses
* Email: [email protected]
*/
(function (exports) {
exports.openTag = '{';
exports.closeTag = '}';
exports.parser = function (code) {
code = code.replace(/^\s/, '');
var args = code.split(' ');
var key = args.shift();
var fuc = exports.keywords[key];
if (fuc) {
args = args.join(' ');
code = fuc.call(code, args);
} else {
code = '=$escape(' + code + ')';
}
return code;
};
exports.keywords = {
'if': function (code) {
return 'if(' + code + '){';
},
'else': function (code) {
code = code.split(' ');
if (code.shift() === 'if') {
code = ' if(' + code.join(' ') + ')';
} else {
code = '';
}
return '}else' + code + '{';
},
'/if': function () {
return '}';
},
'each': function (code) {
code = code.split(' ');
var object = code[0] || '$data';
var as = code[1] || 'as';
var value = code[2] || '$value';
var index = code[3] || '$index';
var args = value + ',' + index;
if (as !== 'as') {
object = '[]';
}
return '$each(' + object + ',function(' + args + '){';
},
'/each': function () {
return '});';
},
'echo': function (code) {
return '=' + code;
},
'include': function (code) {
code = code.split(' ');
var id = code[0];
var data = code[1];
return '=include(' + id + ',' + data + ')';
}
};
exports.helper('$each', function (data, callback) {
if (_isArray(data)) {
_forEach.call(data, callback);
} else {
for (var i in data) {
callback.call(data, data[i], i);
}
}
});
exports.helper('$escape', (function () {
var badChars = /&(?!\w+;)|[<>"']/g;
var map = {
"<": "<",
">": ">",
'"': """,
"'": "'",
"&": "&"
};
var fn = function (s) {
return map[s] || s;
};
return function (content) {
return typeof content === 'string'
? content.replace(badChars, fn)
: content;
};
})());
var _forEach = exports.helper('$forEach');
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
})(template);