1 |
|
2 | var slice = Array.prototype.slice
|
3 |
|
4 | , reHelperFuncHead = /vash\.helpers\.([^= ]+?)\s*=\s*function([^(]*?)\(([^)]*?)\)\s*{/
|
5 | , reHelperFuncTail = /\}$/
|
6 |
|
7 | , reBatchSeparator = /^\/\/\s*@\s*batch\s*=\s*(.*?)$/
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | module.exports = function compile(type, compile, str, options){
|
15 |
|
16 | var separator = type === 'helper'
|
17 | ? reHelperFuncHead
|
18 | : reBatchSeparator;
|
19 |
|
20 | var tpls = splitByNamedTpl(separator, str, function(ma, name){
|
21 | return name.replace(/^\s+|\s+$/, '');
|
22 | }, type === 'helper' ? true : false);
|
23 |
|
24 | if(tpls){
|
25 | Object.keys(tpls).forEach(function(path){
|
26 | tpls[path] = type === 'helper'
|
27 | ? compileSingleHelper(compile, tpls[path], options)
|
28 | : compile('@{' + tpls[path] + '}', options);
|
29 | });
|
30 |
|
31 | tpls.toClientString = function(){
|
32 | return Object.keys(tpls).reduce(function(prev, curr){
|
33 | if(curr === 'toClientString'){
|
34 | return prev;
|
35 | }
|
36 | return prev + tpls[curr].toClientString() + '\n';
|
37 | }, '')
|
38 | }
|
39 | }
|
40 |
|
41 | return tpls;
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 |
|
56 |
|
57 |
|
58 |
|
59 |
|
60 |
|
61 |
|
62 | var splitByNamedTpl = function(reSeparator, markup, resultHandler, keepSeparator){
|
63 |
|
64 | var lines = markup.split(/[\n\r]/g)
|
65 | ,tpls = {}
|
66 | ,paths = []
|
67 | ,currentPath = ''
|
68 |
|
69 | lines.forEach(function(line, i){
|
70 |
|
71 | var pathResult = reSeparator.exec(line)
|
72 | ,handlerResult = pathResult ? resultHandler.apply(pathResult, pathResult) : null
|
73 |
|
74 | if(handlerResult){
|
75 | currentPath = handlerResult;
|
76 | tpls[currentPath] = [];
|
77 | }
|
78 |
|
79 | if((!handlerResult || keepSeparator) && line){
|
80 | tpls[currentPath].push(line);
|
81 | }
|
82 | });
|
83 |
|
84 | Object.keys(tpls).forEach(function(key){
|
85 | tpls[key] = tpls[key].join('\n');
|
86 | })
|
87 |
|
88 | return tpls;
|
89 | }
|
90 |
|
91 | var compileSingleHelper = function(compile, str, options){
|
92 |
|
93 | options = options || {};
|
94 |
|
95 |
|
96 | var def = str.replace(/^[\s\n\r]+|[\s\n\r]+$/, '').match(reHelperFuncHead)
|
97 |
|
98 | ,args = def[3].split(',').map(function(arg){ return arg.replace(' ', '') })
|
99 | ,name = def[1]
|
100 | ,body = str
|
101 | .replace( reHelperFuncHead, '' )
|
102 | .replace( reHelperFuncTail, '' )
|
103 |
|
104 |
|
105 |
|
106 |
|
107 |
|
108 | body = '@{' + body + '}';
|
109 |
|
110 |
|
111 | options.args = args;
|
112 | options.asHelper = name;
|
113 | return compile(body, options);
|
114 | }
|