【发布时间】:2020-12-22 19:03:40
【问题描述】:
有没有办法通过 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
我知道如何为地图执行此操作,我只会使用索引功能。但这不适用于结构,而且我没有灵活性来更改作为上下文传递的底层类型。
有什么想法吗?
【问题讨论】:
-
恕我直言:我宁愿使用地图而不是反射。地图 - 简单、简洁、清晰。反射 - 需要更多代码而且速度很慢......
标签: go go-templates