在传递给模板的数据中,我有两个变量Type
,Res.Type
我想进行比较以为select字段预选择一个选项。
为了说明我的问题,我创建了这个简化的版本:
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) …
Run Code Online (Sandbox Code Playgroud)