微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

通过go模板中的字段名称动态访问结构值

如何解决通过go模板中的字段名称动态访问结构值

是否可以通过go模板中的字段名称动态访问结构值?

对于此代码https://play.golang.org/p/1B1sz0gnbAi):

package main

import (
    "fmt"
    "os"
    "text/template"
)

type Context struct {
    Key string
}

func main() {
    var context = Context{Key: "value"}

    // Success
    var text = `{{ .Key }}`

    t := template.Must(template.New("success").Parse(text))
    _ = t.Execute(os.Stdout,context)

    fmt.Println("")
    
    // Fail
    text = `{{- $key := "Key" }}{{ .$key}}`
    t = template.Must(template.New("fail").Parse(text))
    err := t.Execute(os.Stdout,context)
    if err != nil {
        fmt.Println("executing template:",err)
    }
}

我得到以下输出

value
panic: template: fail:1: unexpected bad character U+0024 '$' in command

goroutine 1 [running]:
text/template.Must(...)
    /usr/local/go-faketime/src/text/template/helper.go:23
main.main()
    /tmp/sandBox897259471/prog.go:26 +0x46b

我知道如何对地图执行此操作,我只会使用索引函数。但这不适用于结构,而且我没有灵活性来更改作为上下文传递的基础类型。

有什么想法吗?

解决方法

即使在常规的golang代码中,按名称访问结构字段也需要反射,因此在模板中也不是那么容易。没有内置函数允许它,我也不知道任何提供此类功能的库。您可以做的就是自己实现该功能。一个非常基本的实现如下:

package main

import (
    "fmt"
    "os"
    "text/template"
    "reflect"
)

type Context struct {
    Key string
}

func FieldByName(c Context,field string) string {
    ref := reflect.ValueOf(c)
    f := reflect.Indirect(ref).FieldByName(field)
    return string(f.String())
}

func main() {

    context := Context{Key: "value"}
    text := `{{- $key := "Key" }}{{ fieldByName . $key}}`
    
    // Custom function map
    funcMap := template.FuncMap{
        "fieldByName": FieldByName,}
    // Add custom functions using Funcs(funcMap)
    t := template.Must(template.New("fail").Funcs(funcMap).Parse(text))
    
    err := t.Execute(os.Stdout,context)
    if err != nil {
        fmt.Println("executing template:",err)
    }
}

go playground

上查看

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。