forked from kof/jqtpl
/
jqtpl.js
399 lines (348 loc) · 11 KB
/
jqtpl.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
/*jslint evil: true*/
/**
* Port of jQuery's Template Engine to Nodejs.
* http://github.com/jquery/jquery-tmpl
*
* Dual licensed under the MIT or GPL Version 2 licenses.
*
*
* @author Oleg Slobodskoi
*/
var toString = Object.prototype.toString;
/**
* Print debugging information to stdout, export print method,
* to let other commonjs systems without "util" to mock it.
* @param {*} data any kind of data.
* @export
*/
exports.debug = function(data) {
var util = require('util');
util.debug.apply(util, arguments);
};
/**
* Iterate over array or object ala jquery.
* @param {Object} obj any plain object.
* @param {Function} callback function.
* @export
*/
exports.each = function(obj, callback) {
var key;
if (obj instanceof Array) {
for (key = 0; key < obj.length; ++key) {
callback.call(obj[key], key, obj[key]);
}
} else {
for (key in obj) {
callback.call(obj[key], key, obj[key]);
}
}
};
/**
* Escape html chars.
* @param {string} str html string.
* @return {string} str escaped html string.
* @export
*/
exports.escape = function(str) {
return String(str)
.replace(/&(?!\w+;)/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
};
/**
* Tags supported by the engine.
* @type {Object}
* @export
*/
exports.tag = {
'tmpl': {
_default: { $2: 'null' },
open: 'if($notnull_1){_=_.concat($item.nest($1,$2));}'
// tmpl target parameter can be of type function, so use $1,
// not $1a (so not auto detection of functions) This means that
// {{tmpl foo}} treats foo as a template (which IS a function).
// Explicit parens can be used if foo is a function that returns
// a template: {{tmpl foo()}}.
},
'wrap': {
_default: { $2: 'null' },
open: '$item.calls(_,$1,$2);_=[];',
close: 'call=$item.calls();_=call._.concat($item.wrap(call,_));'
},
'each': {
_default: { $2: '$index, $value' },
open: 'if($notnull_1){$.each($1a,function($2){with(this){',
close: '}});}'
},
'if': {
open: 'if(($notnull_1) && $1a){',
close: '}'
},
'else': {
_default: { $1: 'true' },
open: '}else if(($notnull_1) && $1a){'
},
'html': {
// Unecoded expression evaluation.
open: 'if($notnull_1){_.push($1a);}'
},
'=': {
// Encoded expression evaluation. Abbreviated form is ${}.
_default: { $1: '$data' },
open: 'if($notnull_1){_.push($.escape($1a));}'
},
'!': {
// Comment tag. Skipped by parser
open: ''
}
};
/**
* Support Express render method (used by Express < 2.0)
*
* @param {string} markup html string.
* @param {Object} options
* `locals` Local variables object.
* `cache` Compiled functions are cached, requires `filename`.
* `filename` Used by `cache` to key caches.
* `scope` Function execution context.
* `debug` Output generated function body.
*
* @return {string} rendered html string.
* @export
*/
exports.render = function(markup, options) {
var name = options.filename || markup,
tpl;
// precompile the template and cache it using filename
exports.template(name, markup);
tpl = exports.tmpl(name, options.locals, options);
if (options.debug) {
exports.debug(exports.template[name]);
}
if (!options.cache) {
delete exports.template[name];
}
return tpl;
};
/**
* Support Express compile method (used by Express >= 2.0)
*
* @param {string} markup html string.
* @param {Object} options
* `locals` Local variables object.
* `cache` Compiled functions are cached, requires `filename`.
* `filename` Used by `cache` to key caches.
* `scope` Function execution context.
* `debug` Output generated function body.
*
* @return {string} rendered html string.
* @export
*/
exports.compile = function(markup, options) {
var name = options.filename || markup;
// precompile the template and cache it using filename
exports.template(name, markup);
return function render(options) {
var tpl = exports.tmpl(name, options);
if (options.debug) {
exports.debug(exports.template[name]);
}
if (!options.cache) {
delete exports.template[name];
}
return tpl;
};
};
/**
* Unescape template.
* @param {string} args template.
* @return {string} args
*/
function unescape(args) {
return args ? args.replace(/\\'/g, "'").replace(/\\"/g, '"').replace(/\\\\/g, '\\') : null;
}
/**
* Build reusable function for template generation
*
* @param {string} markup html string.
* @return {Function} reusable template generator function.
* @export
*/
function buildTmplFn(markup) {
var source = '', breaks = [], tagexp, breakexp, matched, replace, start, finish, line;
tagexp = /\{\{(\/?)(\w+|.)(?:\(((?:[^\}]|\}(?!\}))*?)?\))?(?:\s+(.*?)?)?(\(((?:[^\}]|\}(?!\}))*?)\))?\s*\}\}/g;
// Convert the template into pure JavaScript
markup = markup
.trim()
.replace(/([\\"])/g, '\\$1')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\$\{([^\}]*)\}/g, '{{= $1}}');
// Build index of line-break indexes for source error reporting
breaks = [0];
breakexp = /(?!\\\\)(?:\\r)?\\n/g;
while ((matched = breakexp.exec(markup)) != null) {
breaks.push(matched.index + matched[0].length);
}
// Lookup function to map character offsets in input to
// line/col offsets; we never back up through 'markup',
// so keep track of the line we're on to speed up the
// lookup:
line = 0;
function position(start, finish) {
while (start >= breaks[line+1]) {
line++;
}
return {
line: line+1, //(file line numbers count from 1 not 0)
start: start - breaks[line]+1,
finish: start - breaks[line] + (finish - start)+1
};
}
finish = 0;
while ((matched = tagexp.exec(markup)) != null) {
start = matched.index;
source += markup.slice(finish, start);
finish = start + matched[0].length;
replace = tagsubst.apply(this, [start, finish].concat(matched));
source += replace;
}
source += markup.slice(finish);
function tagsubst(s,f, all, slash, type, fnargs, target, parens, args) {
var tag = exports.tag[type], def, expr, exprAutoFnDetect, err, pos;
if (!tag) {
pos = position(s, f);
err = 'Template command not found: ' + type +
', at ' + pos.line+':'+pos.start+'-'+pos.finish;
err = new Error(err);
err.lineno = pos.line;
err.start = pos.start;
err.finish = pos.finish;
throw err;
}
def = tag._default || [];
if (parens && !/\w$/.test(target)) {
target += parens;
parens = '';
}
if (target) {
target = unescape(target);
args = args ? (',' + unescape(args) + ')') : (parens ? ')' : '');
// Support for target being things like a.toLowerCase();
// In that case don't call with template item as 'this' pointer. Just evaluate...
expr = parens ? (target.indexOf('.') > -1 ? target + unescape(parens) : ('(' + target + ').call($item' + args)) : target;
exprAutoFnDetect = parens ? expr : '(typeof(' + target + ')==="function"?(' + target + ').call($item):(' + target + '))';
} else {
exprAutoFnDetect = expr = def.$1 || 'null';
}
fnargs = unescape(fnargs);
return '");' +
tag[slash ? 'close' : 'open']
.split('$notnull_1').join(target ? 'typeof(' + target + ')!=="undefined" && (' + target + ')!=null' : 'true')
.split('$1a').join(exprAutoFnDetect)
.split('$1').join(expr)
.split('$2').join(fnargs || def.$2 || '') +
'_.push("';
}
var source = (
'var call,_=[],$data=$item.data;' +
// Introduce the data as local variables using with(){}
'with($data){_.push("' +
source +
'");}' +
'return _.join("");'
);
return new Function('$', '$item', source);
}
/**
* Generate reusable function and cache it using name or markup as a key
*
* @param {?string} name of the template.
* @param {string} markup html string.
* @return {Function|undefined} reusable template generator function.
* @export
*/
exports.template = function template(name, markup) {
if (typeof markup !== 'string') {
throw new Error('bad template');
}
if (!name) {
name = markup;
}
var fn = template[name];
if (!fn) {
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
fn = template[name] = buildTmplFn(markup);
}
return fn;
};
/**
* Clear cache
* @export
*/
exports.clearCache = function() {
var cache = exports.template,
name;
for (name in cache) {
if (cache.hasOwnProperty(name)) {
delete cache[name];
}
}
};
/**
* Render template
* @param {string} markup html markup or precompiled markup name.
* @param {*} data can be used in template as template vars.
* @param {Object=} options additional options.
* @return {string} ret rendered markup string.
* @export
*/
exports.tmpl = function(markup, data, options) {
var fn = exports.template(null, markup),
ret = '', i,
res, next;
data = data || {};
options = options || {};
options.data = data;
// overwrite "next" to get an error if the view doesn't exist
if (options.scope && options.scope.res) {
res = options.scope.res;
next = res.req.next;
}
options.nest = function(tmpl, locals) {
var markup, isViewText = false;
if (res && res.partial) {
// overwrite req.next to get the error
res.req.next = function(err) {
if (err) {
isViewText = true;
}
};
// XXX this will not work in the latest express version,
// which is not published yet, 2.0.0
markup = res.partial(tmpl, options, null, locals);
// restore the default behaviour
res.req.next = next;
} else {
isViewText = true;
}
if (isViewText) {
options.locals = locals;
markup = exports.render(tmpl, options);
}
return markup;
};
// don't using Array.isArray() because of couchdb support
if (toString.call(data) === '[object Array]') {
for (i = 0; i < data.length; ++i) {
options.data = data[i];
ret += fn.call(options.scope, exports, options);
}
} else {
ret = fn.call(options.scope, exports, options);
}
return ret;
};