Mercurial > pub > ImplabJs
comparison src/implab/text/template-compile.js @ 0:fc2517695ee1
Initial commit, draft import of existing work
author | cin |
---|---|
date | Thu, 01 Jun 2017 13:20:03 +0300 |
parents | |
children | f0035923ff3e |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:fc2517695ee1 |
---|---|
1 define( | |
2 [ "dojo/request", "./format" ], | |
3 function(request, format) { | |
4 var compile = function(str) { | |
5 var code = "var p=[],print=function(){p.push(foramt.apply(null,arguments));};" + | |
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, | |
47 src : 'implab/template-compile' | |
48 } ]); | |
49 }); | |
50 } | |
51 }; | |
52 | |
53 return compile; | |
54 }); |