This repository has been archived by the owner on Feb 3, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathradiowidget.go
99 lines (84 loc) · 1.78 KB
/
radiowidget.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
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
package gforms
import (
"bytes"
)
type radioSelectWidget struct {
Attrs map[string]string
Maker RadioOptionsMaker
Widget
}
type radioOptionValue struct {
Label string
Value string
Checked bool
Disabled bool
}
type radioOptionValues []*radioOptionValue
type radioContext struct {
Field FieldInterface
Attrs map[string]string
Options radioOptionValues
}
type RadioOptionsMaker func() RadioOptions
type RadioOptions interface {
Label(int) string
Value(int) string
Checked(int) bool
Disabled(int) bool
Len() int
}
type StringRadioOptions [][]string
func (opt StringRadioOptions) Label(i int) string {
return opt[i][0]
}
func (opt StringRadioOptions) Value(i int) string {
return opt[i][1]
}
func (opt StringRadioOptions) Checked(i int) bool {
checked := opt[i][2]
if checked == "true" {
return true
} else {
return false
}
}
func (opt StringRadioOptions) Disabled(i int) bool {
disabled := opt[i][3]
if disabled == "true" {
return true
} else {
return false
}
}
func (opt StringRadioOptions) Len() int {
return len(opt)
}
func (wg *radioSelectWidget) html(f FieldInterface) string {
var buffer bytes.Buffer
ctx := new(radioContext)
opts := wg.Maker()
for i := 0; i < opts.Len(); i++ {
ctx.Options = append(
ctx.Options,
&radioOptionValue{
Label: opts.Label(i),
Value: opts.Value(i),
Checked: opts.Checked(i),
Disabled: opts.Disabled(i),
})
}
ctx.Field = f
ctx.Attrs = wg.Attrs
err := Template.ExecuteTemplate(&buffer, "RadioWidget", ctx)
if err != nil {
panic(err)
}
return buffer.String()
}
// Generate radio input field: <input type="radio" ...>
func RadioSelectWidget(attrs map[string]string, mk RadioOptionsMaker) *radioSelectWidget {
wg := new(radioSelectWidget)
wg.Attrs = attrs
wg.Maker = mk
return wg
}