-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreset-statements.js
More file actions
39 lines (32 loc) · 1.19 KB
/
preset-statements.js
File metadata and controls
39 lines (32 loc) · 1.19 KB
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
var EACH = / *([^,]+)(\s*,\s*([\S]+))? in (\S+)/
module.exports = {
if: function (expression, scope, renderContent, renderOtherwise) {
if( this.eval(expression)(scope) ) return renderContent(scope)
return renderOtherwise(scope)
},
each: function (expression, scope, renderContent) {
var expressions = expression.match(EACH), key, i, n, s
if( !expressions ) throw new Error('each expression is not correct: ' + expression )
var result = '',
item_key = expressions[1],
items = this.eval(expressions[4])(scope),
i_key = expressions[3] || ( items instanceof Array ? '$index' : '$key' )
if( !items || ( !(items instanceof Array) && typeof items !== 'object' ) ) throw new TypeError('list in expression should be a non null Object or an Array')
if( items instanceof Array ) {
for( i = 0, n = items.length ; i < n ; i++ ) {
s = Object.create(scope)
s[i_key] = i
s[item_key] = items[i]
result += renderContent(s)
}
} else {
for( key in items ) {
s = Object.create(scope)
s[i_key] = key
s[item_key] = items[key]
result += renderContent(s)
}
}
return result
},
}