-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy patheach_helper.go
54 lines (51 loc) · 1.22 KB
/
each_helper.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
package velvet
import (
"bytes"
"html/template"
"reflect"
"github.com/pkg/errors"
)
func eachHelper(collection interface{}, help HelperContext) (template.HTML, error) {
out := bytes.Buffer{}
val := reflect.ValueOf(collection)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
if val.Kind() == reflect.Struct || val.Len() == 0 {
s, err := help.ElseBlock()
return template.HTML(s), err
}
switch val.Kind() {
case reflect.Array, reflect.Slice:
for i := 0; i < val.Len(); i++ {
v := val.Index(i).Interface()
ctx := help.Context.New()
ctx.Set("@first", i == 0)
ctx.Set("@last", i == val.Len()-1)
ctx.Set("@index", i)
ctx.Set("@value", v)
s, err := help.BlockWith(ctx)
if err != nil {
return "", errors.WithStack(err)
}
out.WriteString(s)
}
case reflect.Map:
keys := val.MapKeys()
for i := 0; i < len(keys); i++ {
key := keys[i].Interface()
v := val.MapIndex(keys[i]).Interface()
ctx := help.Context.New()
ctx.Set("@first", i == 0)
ctx.Set("@last", i == len(keys)-1)
ctx.Set("@key", key)
ctx.Set("@value", v)
s, err := help.BlockWith(ctx)
if err != nil {
return "", errors.WithStack(err)
}
out.WriteString(s)
}
}
return template.HTML(out.String()), nil
}