Reputation: 341
I am new to golang. I would like to pass multiple variables to html. So I have a type like:
type Variables struct {
UserNames []string
Checks []string
}
pagevarible with passed the correct values
var PageVars Variables
PageVars = Variables{
UserNames: ulist,
Checks: check,
}
log.Println("ulist",ulist)
err = tpl.Execute(w, PageVars) //execute the template and pass it to index page
if err != nil { // if there is an error
log.Print("template executing error: ", err) //log it on terminal
}
And I want to pass both UserNames and Checks to html template, something like:
{{range .UserNames .Checks}}
{{.UserNames}}: <input type="checkbox" name="email" value={{. UserNames}} {{.Checks}}/><br />
{{end}}
But it didn't work out. Can anyone correct my syntax? Thanks a lot.
Upvotes: 3
Views: 4914
Reputation: 120941
Range with an index variable, use that index to get the check:
{{range $i, $user := .UserNames}}
{{$check := index $.Checks $i}}
{{$user}}: <input type="checkbox" name="email" value={{$user}} {{$check}}/><br />
{{end}}
Range sets the cursor .
to successive values of the slice. Use $
to reference the Checks
field in the argument to the template.
Upvotes: 5
Reputation: 19040
When you reference fields via .
inside a range, its expecting that to be a field on the item being ranged, so in this case
{{range .UserNames}}
{{$check := .Checks}}
Its looking for a Checks field on the current instance in the Usernames list. If checks is separate to that (as it appears in your PageVars), then you can use the $
reference to the top level object, e.g.
{{range .UserNames}}
{{$check := $.Checks}}
You didn't post the code executing the template, but make sure you're checking the error returned from it.
Upvotes: 3