【发布时间】:2017-11-27 19:21:46
【问题描述】:
在我传递给我的模板的数据中,我有两个变量 Type 和 Res.Type 我想比较以便为我的选择字段预选一个选项。
为了说明我的问题,我创建了这个简化版本:
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())
}
它应该选择"FindAllString" 选项但它只会产生错误
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
当我只比较两个普通字符串时,它可以工作,但我想知道是否有一种惯用的方法来做到这一点。我已经看到你可以在模板中添加一个函数,但我觉得必须有一个更简单的方法。
【问题讨论】:
标签: html loops go go-templates