Templates parsing checkboxes

I am trying to process checkboxes in go template forms…

What is the efficient way to check if a checkbox is checked from an array of options?

I have:

data := make(map[string]interface{})
data["User"] = user
data["Roles"] = []string{"User", "Admin"}
tmpl := template.Must(template.ParseFiles("templates/admin/user.gohtml"))
tmpl.Execute(w, data)

And want to parse it like this:

{{range .Roles}}
    <input name="roles" type="checkbox" id="roles{{.}}" value="{{.}}" 
       {{if eq . .User.Roles}}checked{{end}}/>
    <label for="roles{{.}}">{{.}}</label>

So… To check if it is checked efficiently, I need an “in” operator. i.e. {{if in . .User.Roles}}. I’m sure I can solve it the hard way. But what is the correct way? They must have thought of this…


Okay… Came up with this. Please let me know if this is the best way to solve it?

Moral of the story is that dot is misleading and to use variables to be more clear…

{{$roles := .Roles}}
{{$userroles := .User.Roles}}
{{range $role := $roles}}
    <input name="roles" type="checkbox" id="roles{{$role}}" value="{{$role}}" 
        {{range $userrole := $userroles}}
            {{if eq $role $userrole}}checked{{end}}
    <label for="roles{{$role}}">{{$role}}</label>
1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.