Home > Enterprise >  Can not use ENUM in template
Can not use ENUM in template

Time:11-11

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?

CodePudding user response:

You can register template functions with the Funcs method for each of your enums, given them the same name as the enum's constant has, and then invoke the function within the template by simply referencing them.

i.e. to be able to do eq $v Admin inside a template you can do the following:

type flag int

const (
    Admin flag = iota   1 // iota = 0
    // ...
)

var funcMap = template.FuncMap{
    "Admin":  func() flag { return Admin },
    // ...
}

var file = `{{ $v := . }}
{{- if eq $v Admin }}is admin{{ else }}is not admin{{ end }}
`

func main() {
    t := template.Must(template.New("t").Funcs(funcMap).Parse(file))

    for _, v := range []interface{}{Admin, 1234} {
        if err := t.Execute(os.Stdout, v); err != nil {
            panic(err)
        }
        fmt.Println("----------------")
    }
}

https://play.golang.org/p/70O7ebuYuNX

is admin
----------------
is not admin
----------------

You can also declare a method on the flag type and use the method value as the template function to make it more neat:

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))

    for _, v := range []interface{}{Admin, Editor, 1234} {
        if err := t.Execute(os.Stdout, v); err != nil {
            panic(err)
        }
        fmt.Println("----------------")
    }
}

https://play.golang.org/p/4JLsqxoHs8H

is admin
is not editor
----------------
is not admin
is editor
----------------
is not admin
is not editor
----------------
  •  Tags:  
  • go
  • Related