Mercurial > pub > ImplabJs
annotate src/implab/text/template-compile.js @ 12:23be39fd3851
fixed typo in template-compile the built-in function 'print'
author | cin |
---|---|
date | Thu, 24 Aug 2017 04:30:11 +0300 |
parents | f0035923ff3e |
children | 7c22fc01fcec |
rev | line source |
---|---|
0 | 1 define( |
2 [ "dojo/request", "./format" ], | |
3 function(request, format) { | |
4 var compile = function(str) { | |
12
23be39fd3851
fixed typo in template-compile the built-in function 'print'
cin
parents:
8
diff
changeset
|
5 var code = "var p=[],print=function(){p.push(format.apply(null,arguments));};" + |
0 | 6 // Introduce the data as local variables using with(){} |
7 "with(obj){p.push('" + | |
8 // Convert the template into pure JavaScript | |
9 str.replace(/[\r\t\n]/g, " ").split("<%").join("\t").replace( | |
10 /(^|%>)[^\t]*/g, | |
11 function(x) { | |
12 return x.replace(/('|\\)/g, "\\$1"); | |
13 }).replace(/\t=(.*?)%>/g, "',$1,'").split("\t").join("');") | |
14 .split("%>").join("p.push('") + "');}return p.join('');"; | |
15 /* jshint -W054 */ | |
16 try { | |
17 var compiled = new Function("obj, format, nls", code); | |
18 | |
19 /** | |
20 * Функция форматирования по шаблону | |
21 * | |
22 * @type{Function} | |
23 * @param{Object} obj объект с параметрами для подстановки | |
24 */ | |
25 return function(obj) { | |
26 return compiled(obj || {}, format); | |
27 }; | |
28 } catch (e) { | |
29 if (console && console.error) { | |
30 console.error(code); | |
31 } | |
32 } | |
33 }; | |
34 | |
35 var cache = {}; | |
36 | |
37 compile.load = function(id, require, callback) { | |
38 var url = require.toUrl(id); | |
39 if (url in cache) { | |
40 callback(cache[url]); | |
41 } else { | |
42 request(url).then(compile).then(function(tc) { | |
43 callback(cache[url] = tc); | |
44 }, function(err) { | |
45 require.signal("error", [ { | |
46 error : err, | |
8 | 47 src : 'implab/text/template-compile' |
0 | 48 } ]); |
49 }); | |
50 } | |
51 }; | |
52 | |
53 return compile; | |
54 }); |