我想检查传递给
template.Exec
函数的数据中是否存在键(不存在!=零值)。使用 {{if
或 {{with
有效,但前提是键的值不是零值。
当 Num (int) 存在但其值为 {{if .Num}}
时,
0
计算结果为 false。
要检查传递给 Go 中文本/模板的数据中是否存在键,可以使用
{{if .KeyName}}
语法。但是,正如您所指出的,如果与 KeyName
关联的值是其类型的零值,则这将计算为 false。
要克服此限制并检查键是否存在(无论其值是否为零),您可以通过定义自定义函数来使用技巧。方法如下:
这是一个例子:
package main
import (
"fmt"
"os"
"text/template"
)
func KeyExists(key string, data interface{}) bool {
// Use reflection to check if the key exists in the data
v := reflect.ValueOf(data)
if v.Kind() == reflect.Map {
return v.MapIndex(reflect.ValueOf(key)).IsValid()
}
return false
}
func main() {
// Sample data
data := map[string]interface{}{
"Num": 0,
}
// Create a new template and register the custom function
tmpl := template.New("example")
tmpl.Funcs(template.FuncMap{
"KeyExists": KeyExists,
})
// Parse the template
_, err := tmpl.Parse(`
{{if KeyExists "Num" .}}Key "Num" exists{{else}}Key "Num" does not exist{{end}}
{{if KeyExists "Name" .}}Key "Name" exists{{else}}Key "Name" does not exist{{end}}
`)
if err != nil {
fmt.Println("Error parsing template:", err)
return
}
// Execute the template
err = tmpl.Execute(os.Stdout, data)
if err != nil {
fmt.Println("Error executing template:", err)
return
}
}
在此示例中,
KeyExists
函数使用反射来检查所提供的数据中是否存在该键。然后,我们在模板中注册这个函数,并在模板中使用它来检查键是否存在,无论它们的值如何。