forked from goofychris/art-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.js
509 lines (331 loc) · 10.9 KB
/
template.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
/*!
* artTemplate - Template Engine
* https://github.com/aui/artTemplate
* Released under the MIT, BSD, and GPL Licenses
* Email: [email protected]
*/
/**
* 模板引擎路由函数
* 若第二个参数类型为 Object 则执行 render 方法, 否则 compile 方法
* @name template
* @param {String} 模板ID (可选)
* @param {Object, String} 数据或者模板字符串
* @return {String, Function} 渲染好的HTML字符串或者渲染方法
*/
var template = function (id, content) {
return template[
typeof content === 'object' ? 'render' : 'compile'
].apply(template, arguments);
};
(function (exports, global) {
"use strict";
exports.version = '1.4.0';
exports.openTag = '<%';
exports.closeTag = '%>';
exports.parser = null;
/**
* 渲染模板
* @name template.render
* @param {String} 模板ID
* @param {Object} 数据
* @return {String} 渲染好的HTML字符串
*/
exports.render = function (id, data) {
var cache = _getCache(id);
if (cache === undefined) {
return _debug({
id: id,
name: 'Render Error',
message: 'Not Cache'
});
}
return cache(data);
};
/**
* 编译模板
* 2012-6-6:
* define 方法名改为 compile,
* 与 Node Express 保持一致,
* 感谢 TooBug 提供帮助!
* @name template.compile
* @param {String} 模板ID (可选)
* @param {String} 模板字符串
* @return {Function} 渲染方法
*/
exports.compile = function (id, source) {
var debug = arguments[2];
if (typeof source !== 'string') {
debug = source;
source = id;
id = null;
}
try {
var Render = _compile(source, debug);
} catch (e) {
e.id = id || source;
e.name = 'Syntax Error';
return _debug(e);
}
function render (data) {
try {
return new Render(data).template;
} catch (e) {
if (!debug) {
return exports.compile(id, source, true)(data);
}
e.id = id || source;
e.name = 'Render Error';
e.source = source;
return _debug(e);
};
};
render.prototype = Render.prototype;
render.toString = function () {
return Render.toString();
};
if (id) {
_cache[id] = render;
}
return render;
};
/**
* 扩展模板公用辅助方法
* @name template.helper
* @param {String} 名称
* @param {Function} 方法
*/
exports.helper = function (name, helper) {
_helpers[name] = helper;
};
var _cache = {};
var _isNewEngine = ''.trim;
var _isServer = _isNewEngine && !global.document;
var _keyWordsMap = {};
var _forEach = function () {
var forEach = Array.prototype.forEach || function (block, thisObject) {
var len = this.length >>> 0;
for (var i = 0; i < len; i++) {
if (i in this) {
block.call(thisObject, this[i], i, this);
}
}
};
return function (array, callback) {
forEach.call(array, callback);
};
}();
var _create = Object.create || function (object) {
function Fn () {};
Fn.prototype = object;
return new Fn;
};
var _helpers = exports.prototype = {
$forEach: _forEach,
$render: exports.render,
$getValue: function (value) {
return value === undefined ? '' : value;
}
};
// javascript 关键字表
_forEach((
// 关键字
'break,case,catch,continue,debugger,default,delete,do,else,false,finally,for,function,if'
+ ',in,instanceof,new,null,return,switch,this,throw,true,try,typeof,var,void,while,with'
// 保留字
+ ',abstract,boolean,byte,char,class,const,double,enum,export,extends,final,float,goto'
+ ',implements,import,int,interface,long,native,package,private,protected,public,short'
+ ',static,super,synchronized,throws,transient,volatile'
// ECMA 5 - use strict
+ ',arguments,let,yield'
).split(','), function (key) {
_keyWordsMap[key] = true;
});
// 模板编译器
var _compile = function (source, debug) {
var openTag = exports.openTag;
var closeTag = exports.closeTag;
var parser = exports.parser;
var code = source;
var tempCode = '';
var line = 1;
var uniq = {$out:true,$line:true};
var variables = "var $helpers=this,"
+ (debug ? "$line=0," : "");
var replaces = _isNewEngine
? ["$out='';", "$out+=", ";", "$out"]
: ["$out=[];", "$out.push(", ");", "$out.join('')"];
var concat = _isNewEngine
? "if(content!==undefined){$out+=content;return content}"
: "$out.push(content);";
var print = "function(content){" + concat + "}";
var include = "function(id,data){"
+ "if(data===undefined){data=$data}"
+ "var content=$helpers.$render(id,data);"
+ concat
+ "}";
// html与逻辑语法分离
_forEach(code.split(openTag), function (code, i) {
code = code.split(closeTag);
var $0 = code[0];
var $1 = code[1];
// code: [html]
if (code.length === 1) {
tempCode += html($0);
// code: [logic, html]
} else {
tempCode += logic($0);
if ($1) {
tempCode += html($1);
}
}
});
code = tempCode;
// 调试语句
if (debug) {
code = 'try{' + code + '}catch(e){'
+ 'e.line=$line;'
+ 'throw e'
+ '}';
}
code = variables + replaces[0] + code + 'this.template=' + replaces[3];
try {
var render = new Function('$data', code);
var proto = render.prototype = _create(_helpers);
proto.toString = function () {
return this.template;
};
return render;
} catch (e) {
e.temp = 'function anonymous($data) {' + code + '}';
throw e;
};
// 处理 HTML 语句
function html (code) {
// 记录行号
line += code.split(/\n/).length - 1;
code = code
// 单双引号与反斜杠转义
.replace(/('|"|\\)/g, '\\$1')
// 换行符转义(windows + linux)
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n');
code = replaces[1] + "'" + code + "'" + replaces[2];
return code + '\n';
};
// 处理逻辑语句
function logic (code) {
var thisLine = line;
if (parser) {
// 语法转换器
code = parser(code);
} else if (debug) {
// 记录行号
code = code.replace(/\n/g, function () {
line ++;
return '$line=' + line + ';';
});
}
// 输出语句
if (code.indexOf('=') === 0) {
code = code.substring(1).replace(/[\s;]*$/, '');
if (_isNewEngine) {
// $getValue: undefined 转化为空字符串
code = '$getValue(' + code + ')';
}
code = replaces[1] + code + replaces[2];
}
if (debug) {
code = '$line=' + thisLine + ';' + code;
}
getKey(code);
return code + '\n';
};
// 提取模板中的变量名
function getKey (code) {
// 过滤注释、字符串、方法名
code = code.replace(/\/\*.*?\*\/|'[^']*'|"[^"]*"|\.[\$\w]+/g, '');
// 分词
_forEach(code.split(/[^\$\w\d]+/), function (name) {
// 沙箱强制语法规范:禁止通过套嵌函数的 this 关键字获取全局权限
if (/^this$/.test(name)) {
throw {
message: 'Prohibit the use of the "' + name + '"'
};
}
// 过滤关键字与数字
if (!name || _keyWordsMap.hasOwnProperty(name) || /^\d/.test(name)) {
return;
}
// 除重
if (!uniq.hasOwnProperty(name)) {
setValue(name);
uniq[name] = true;
}
});
};
// 声明模板变量
// 赋值优先级: 内置特权方法(include, print) > 公用模板辅助方法 > 数据
function setValue (name) {
var value;
if (name === 'print') {
value = print;
} else
if (name === 'include') {
value = include;
} else
if (_helpers.hasOwnProperty(name)) {
value = '$helpers.' + name;
} else {
value = '$data.' + name;
}
variables += name + '=' + value + ',';
};
};
// 获取模板缓存
var _getCache = function (id) {
var cache = _cache[id];
if (cache === undefined && !_isServer) {
var elem = document.getElementById(id);
if (elem) {
exports.compile(id, elem.value || elem.innerHTML);
}
return _cache[id];
} else if (_cache.hasOwnProperty(id)) {
return cache;
}
};
// 模板调试器
var _debug = function (e) {
var content = '[template]:\n'
+ e.id
+ '\n\n[name]:\n'
+ e.name;
if (e.message) {
content += '\n\n[message]:\n'
+ e.message;
}
if (e.line) {
content += '\n\n[line]:\n'
+ e.line;
content += '\n\n[source]:\n'
+ e.source.split(/\n/)[e.line - 1].replace(/^[\s\t]+/, '');
}
if (e.temp) {
content += '\n\n[temp]:\n'
+ e.temp;
}
if (global.console) {
console.error(content);
}
function error () {
return error + '';
};
error.toString = function () {
return '{Template Error}';
};
return error;
};
})(template, this);
if (typeof module !== 'undefined' && module.exports) {
module.exports = template;
}