亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 go 模板中通過字段名動態訪問結構值

在 go 模板中通過字段名動態訪問結構值

Go
慕無忌1623718 2022-06-27 15:39:48
有沒有辦法通過 go 模板中的字段名動態訪問結構值?對于此代碼(https://play.golang.org/p/1B1sz0gnbAi):package mainimport (    "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)    }}我得到這個輸出:valuepanic: template: fail:1: unexpected bad character U+0024 '$' in commandgoroutine 1 [running]:text/template.Must(...)    /usr/local/go-faketime/src/text/template/helper.go:23main.main()    /tmp/sandbox897259471/prog.go:26 +0x46b我知道如何為地圖執行此操作,我只會使用索引函數。但這不適用于結構,并且我沒有靈活性來更改作為上下文傳遞的基礎類型。有任何想法嗎?
查看完整描述

1 回答

?
HUH函數

TA貢獻1836條經驗 獲得超4個贊

即使在常規的 golang 代碼中,按名稱訪問結構字段也需要反射,因此在模板中也不是那么容易。沒有允許它的內置函數,我也不知道有任何庫提供這樣的功能。您可以做的是自己實現該功能。一個非?;镜膶崿F可能如下:


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)

    }

}



查看完整回答
反對 回復 2022-06-27
  • 1 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號