In the data I pass to my template I have the two variables Type
and Res.Type
I want to compare to preselect an option for my select field.
To illustrate my problem I have created this simplified version:
package main
import (
"bufio"
"bytes"
"html/template"
"log"
)
type Result struct{ Type string }
func main() {
types := map[string]string{
"FindAllString": "FindAllString",
"FindString": "FindString",
"FindStringSubmatch": "FindStringSubmatch",
}
res := &Result{Type: "findAllString"}
templateString := `
<select name="type">
{{ range $key,$value := .Types }}
{{ if eq $key .Res.Type }}
<option value="{{$key}}" selected>{{$value}}</option>
{{ else }}
<option value="{{$key}}">{{$value}}</option>
{{ end }}
{{ end }}
</select>`
t, err := template.New("index").Parse(templateString)
if err != nil {
panic(err)
}
var b bytes.Buffer
writer := bufio.NewWriter(&b)
err = t.Execute(writer, struct {
Types map[string]string
Res *Result
}{types, res})
if err != nil {
panic(err)
}
writer.Flush()
log.Println(b.String())
}
It should select the "FindAllString"
option but it only generates the error
panic: template: index:4:21: executing "index" at <.Res.Type>: can't evaluate field Res in type string
goroutine 1 [running]:
panic(0x53f6e0, 0xc4200144c0)
/usr/local/go/src/runtime/panic.go:500 +0x1a1
main.main()
/home/tobias/ngo/src/github.com/gamingcoder/tmp/main.go:41 +0x523
exit status 2
When I just compare two normal strings it works but I want to know if there is an idomatic way to do this. I have seen that you could add a function to the template but I feel that there must be a simpler way for this.