问题是{{range}}
动作改变(设置)点(.
)即使您使用循环变量($key
and $value
)在你的情况下。里面一个{{range}}
点设置为当前元素。
还有里面{{range}}
你写:
{{ if eq $key .Res.Type }}
由于循环中的值是string
价值观,.Res.Type
是一个错误,因为没有Res
的字段或方法string
值(由点表示的当前元素.
).
Use the $
符号不引用循环值,而是引用传递给模板执行的参数:
{{ if eq $key $.Res.Type }}
这可以工作,但不会给你想要的输出,因为你有一个拼写错误:
res := &Result{Type: "findAllString"}
使用大写字母Result
身为你的types
地图还包含大写字母的值:
res := &Result{Type: "FindAllString"}
这样你就可以获得所需的输出(在去游乐场 https://play.golang.org/p/ZtZAoeOtF3):
2009/11/10 23:00:00
<select name="type">
<option value="FindAllString" selected>FindAllString</option>
<option value="FindString">FindString</option>
<option value="FindStringSubmatch">FindStringSubmatch</option>
</select>
另请注意,您可以简单地编写如下循环:
{{range $key, $value := .Types}}
<option value="{{$key}}"{{if eq $key $.Res.Type}} selected{{end}}>{{.}}</option>
{{end}}
另请注意,出于测试目的,您可以简单地通过os.Stdout
作为模板执行的编写者,您将在控制台上看到结果,而无需创建和使用缓冲区,例如:
err = t.Execute(os.Stdout, struct {
Types map[string]string
Res *Result
}{types, res})
尝试使用简化版本去游乐场 https://play.golang.org/p/pEvOsU-bNS.
阅读此答案以获取更多见解:golang 模板引擎管道 https://stackoverflow.com/questions/42507958/golang-template-engine-pipelines/42508255#42508255