-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy pathranger_test.go
69 lines (59 loc) · 1.55 KB
/
ranger_test.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
package jet
import (
"fmt"
"os"
"reflect"
)
// exampleCustomBenchRanger satisfies the Ranger interface, generating fixed
// data.
type exampleCustomRanger struct {
i int
}
// Type assertion to verify exampleCustomRanger satisfies the Ranger interface.
var _ Ranger = (*exampleCustomRanger)(nil)
func (ecr *exampleCustomRanger) ProvidesIndex() bool {
// Return false if 'k' can't be filled in Range().
return true
}
func (ecr *exampleCustomRanger) Range() (k reflect.Value, v reflect.Value, done bool) {
if ecr.i >= 3 {
done = true
return
}
k = reflect.ValueOf(ecr.i)
v = reflect.ValueOf(fmt.Sprintf("custom ranger %d", ecr.i))
ecr.i += 1
return
}
// ExampleRanger demonstrates how to write a custom template ranger.
func ExampleRanger() {
// Error handling ignored for brevity.
//
// Setup template and rendering.
loader := NewInMemLoader()
loader.Set("template",
`{{ range k := ecr }}
{{k}} = {{.}}
{{- end }}
{{ range k := struct.RangerEface }}
{{k}} = {{.}}
{{- end }}`,
)
set := NewSet(loader, WithSafeWriter(nil))
t, _ := set.GetTemplate("template")
// Pass a custom ranger instance as the 'ecr' var, as well as in a struct field with type interface{}.
vars := VarMap{
"ecr": reflect.ValueOf(&exampleCustomRanger{}),
"struct": reflect.ValueOf(struct{ RangerEface interface{} }{RangerEface: &exampleCustomRanger{}}),
}
// Execute template.
_ = t.Execute(os.Stdout, vars, nil)
// Output:
// 0 = custom ranger 0
// 1 = custom ranger 1
// 2 = custom ranger 2
//
// 0 = custom ranger 0
// 1 = custom ranger 1
// 2 = custom ranger 2
}