1 回答

TA貢獻1836條經(jīng)驗 獲得超4個贊
即使在常規(guī)的 golang 代碼中,按名稱訪問結(jié)構(gòu)字段也需要反射,因此在模板中也不是那么容易。沒有允許它的內(nèi)置函數(shù),我也不知道有任何庫提供這樣的功能。您可以做的是自己實現(xiàn)該功能。一個非?;镜膶崿F(xiàn)可能如下:
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)
}
}
- 1 回答
- 0 關(guān)注
- 150 瀏覽
添加回答
舉報