Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not use ENUM in template

Tags:

go

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?

like image 417
Hasan A Yousef Avatar asked Oct 23 '25 06:10

Hasan A Yousef


1 Answers

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
----------------
like image 92
mkopriva Avatar answered Oct 25 '25 10:10

mkopriva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!