テンプレートに渡すデータには、2つの変数Type
とRes.Type
があります。私の選択フィールドのオプションをあらかじめ選択するために比較したいです。それは"FindAllString"
オプションを選択してくださいGoテンプレート内の2つの変数を比較
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())
}
が、私はちょうどそれが動作する2つの通常の文字列を比較するとそれだけでエラーに
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
を生成します。私は、この簡易版を作成している私の問題を説明するために
私はこれを行うための愚かな方法があるかどうかを知りたい。私はあなたがテンプレートに関数を追加できることを見てきましたが、私はこれのためのより簡単な方法が必要であると感じています。