在golang template内部,只需输出值,似乎指针会自动解除引用。当.ID
是指向int
的指针时,
{{.ID}}
输出5
但是当我尝试在管道中使用它时,{{if eq .ID 5}}
我收到错误。
executing "mytemplate" at <eq .ID 5>: error calling eq: invalid type for comparison
如何在模板管道中取消引用指针?
答案 0 :(得分:5)
一种方法是注册一个取消引用指针的自定义函数,这样你就可以将结果与你想要的结果进行比较,或者用它做任何其他事情。
例如:
func main() {
t := template.Must(template.New("").Funcs(template.FuncMap{
"Deref": func(i *int) int { return *i },
}).Parse(src))
i := 5
m := map[string]interface{}{"ID": &i}
if err := t.Execute(os.Stdout, m); err != nil {
fmt.Println(err)
}
}
const src = `{{if eq 5 (Deref .ID)}}It's five.{{else}}Not five: {{.ID}}{{end}}`
输出:
It's five.
或者你可以使用一个不同的自定义函数来获取指针和非指针,并进行比较,例如:
"Cmp": func(i *int, j int) bool { return *i == j },
从模板中调用它:
{{if Cmp .ID 5}}It's five.{{else}}Not five: {{.ID}}{{end}}
输出是一样的。请在Go Playground上尝试这些。