如何检查 Go 中文本模板数据中是否存在某个键?

问题描述 投票:0回答:1

我想检查传递给

template.Exec
函数的数据中是否存在键(不存在!=零值)。使用
{{if
{{with
有效,但前提是键的值不是零值。

当 Num (int) 存在但其值为

{{if .Num}}

 时,
0
计算结果为 false。

go templates text
1个回答
-1
投票

要检查传递给 Go 中文本/模板的数据中是否存在键,可以使用

{{if .KeyName}}
语法。但是,正如您所指出的,如果与
KeyName
关联的值是其类型的零值,则这将计算为 false。

要克服此限制并检查键是否存在(无论其值是否为零),您可以通过定义自定义函数来使用技巧。方法如下:

  1. 定义一个自定义函数,它接受键名称和数据并返回一个布尔值,指示该键是否存在。
  2. 将此自定义函数注册到模板中。
  3. 在模板中使用此自定义函数来检查密钥是否存在。

这是一个例子:

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
函数使用反射来检查所提供的数据中是否存在该键。然后,我们在模板中注册这个函数,并在模板中使用它来检查键是否存在,无论它们的值如何。

© www.soinside.com 2019 - 2024. All rights reserved.