hyousef
(Hasan Yousef)
November 9, 2021, 7:31pm
1
in my code i defined an enum as below:
type flag int
const (
Admin flag = iota + 1 // iota = 0
Editer
Superuser
Viewer
)
The info is passed to the template, and I do a comparison like:
{{range $i, $v := .Flags}}
{{if or (eq $v 1) (eq $v 3)}}
<input type="text" name="subject" placeholder= {{$v}} required>
{{else}}
<input type="text" name="subject" placeholder= {{$v}} disabled>
{{end}}
{{end}}
As seen here, the comparison is done with the equivalent int eq $v 1
, what I like to do is something like eq $v Admin
so I use the enum name instead of its value.
Can I do this?
hyousef
(Hasan Yousef)
November 10, 2021, 3:23pm
2
I found the solution using Method Values as here
package main
import (
"fmt"
"os"
"text/template"
)
type flag int
func (f flag) get() flag { return f }
const (
Admin flag = iota + 1 // iota = 0
Editor
)
var funcMap = template.FuncMap{
"Admin": Admin.get,
"Editor": Editor.get,
// ...
}
var file = `{{ $v := . }}
{{- if eq $v Admin }}is admin{{ else }}is not admin{{ end }}
{{ if eq $v Editor }}is editor{{ else }}is not editor{{ end }}
`
func main() {
t := template.Must(template.New("t").Funcs(funcMap).Parse(file))
if err := t.Execute(os.Stdout, Admin); err != nil {
panic(err)
}
fmt.Println("----------------")
if err := t.Execute(os.Stdout, Editor); err != nil {
panic(err)
}
fmt.Println("----------------")
if err := t.Execute(os.Stdout, 1234); err != nil {
panic(err)
}
fmt.Println("----------------")
}