-
Notifications
You must be signed in to change notification settings - Fork 0
/
foreach.go
70 lines (64 loc) · 1.69 KB
/
foreach.go
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
package xtpl
import (
"bytes"
"strings"
)
func (x *xtpl) execForeach(src []rune) func(vars *xVarCollection) []byte {
var sliceName, iteratorName, valueName string
var hasIterator = false
var bracketEnd = getOffset(src, ")", "", true, true)
var expr = src[1:bracketEnd]
var content = x.buildTree(src[bracketEnd+1:], true)
var asPosition = getOffset(expr, " as ", "", true, true)
if asPosition > 0 {
sliceName = strings.TrimSpace(string(expr[:asPosition]))
} else {
return func(vars *xVarCollection) []byte {
return []byte("Parse error")
}
}
if toPosition := getOffset(expr[asPosition+4:], "=>", "", true, true); toPosition > 0 {
iteratorName = strings.TrimSpace(string(expr[asPosition+4 : asPosition+4+toPosition]))
valueName = strings.TrimSpace(string(expr[asPosition+4+toPosition+2 : bracketEnd-1]))
hasIterator = true
} else {
valueName = strings.TrimSpace(string(expr[asPosition+4 : bracketEnd-1]))
}
var sliceFunc = x.exec([]rune(sliceName))
return func(vars *xVarCollection) []byte {
var buff = &bytes.Buffer{}
var value = sliceFunc(vars)
var pos = uint(0)
switch value.vType {
case varTypeMap:
for key, val := range value.toMap() {
if hasIterator {
vars.setVar(iteratorName, key)
}
vars.setVar(valueName, val.toInterface())
for _, f := range content {
buff.Write(f(vars))
}
pos++
if pos >= cyclesLimit {
break
}
}
default:
for i, val := range value.toSlice() {
if hasIterator {
vars.setVar(iteratorName, i)
}
vars.setVar(valueName, val.toInterface())
for _, f := range content {
buff.Write(f(vars))
}
pos++
if pos >= cyclesLimit {
break
}
}
}
return buff.Bytes()
}
}