第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

在 Go 模板中按名稱訪問結(jié)構(gòu)成員

在 Go 模板中按名稱訪問結(jié)構(gòu)成員

Go
動漫人物 2022-04-26 19:45:03
我希望創(chuàng)建一個通用/通用的 Go html 模板,它將根據(jù)其輸入生成一個標準的 html 表。我曾希望按名稱查找結(jié)構(gòu)成員,但我無法完成這項工作。我環(huán)顧四周,找不到解決方案,所以我要么遺漏了一些明顯的東西,要么方法是錯誤的。在這方面,我會接受一種解決方案,該解決方案顯示了一種替代或更好的方法,可以避免嘗試這種查找。示例模板:{{ $fields := .FieldMap }}<table>    <thead>    <tr>    {{ range $key, $value := $fields }}        <th>{{ $key }}</th>    {{ end }}    </tr>    </thead>    <tbody>    {{ range $i, $v :=  .Model }}    <tr>        {{ $rowData := . }}{{/* FAILS: error calling index: can't index item of type main.Person  <td> {{ index . "FirstName"}}</td>*/}}        {{ range $key, $value := $fields }}{{/* FAILS: error calling index: can't index item of type main.Person   <td> {{ index $rowData $value }}</td>*/}}{{/* FAILS: bad character U+0024 '$'                                    <td> {{ $rowData.$value }}</td>*/}}        {{ end }}    </tr>    {{ end }}    </tbody></table>示例圍棋:包主import (    "html/template"    "os")type Person struct {    FirstName string    LastName string}type Animal struct {    Species string}type TemplateData struct {    Model interface{}    FieldMap map[string]string}func main() {    t, err := template.ParseFiles("table.gohtml")    if err != nil {        panic(err)    }    // Here we use Person, but I may want to pass other types of struct to the template, for example "Animal"    dataPerson := TemplateData{        Model: []Person{            {                FirstName: "Test",                LastName:  "Template",            },        },        FieldMap: map[string]string{"First": "FirstName", "Last": "LastName"},    }    err = t.Execute(os.Stdout, dataPerson)    if err != nil {        panic(err)    }}我希望它清楚我想要做什么 - 有一個模板,我可以在各種類型的結(jié)構(gòu)中重用它。
查看完整描述

1 回答

?
繁花不似錦

TA貢獻1851條經(jīng)驗 獲得超4個贊

創(chuàng)建一個模板函數(shù),將結(jié)構(gòu)字段名稱和值作為映射返回:


// fields returns map of field names and values for struct s.

func fields(s interface{}) (map[string]interface{}, error) {

    v := reflect.Indirect(reflect.ValueOf(s))

    if v.Kind() != reflect.Struct {

        return nil, fmt.Errorf("%T is not a struct", s)

    }

    m := make(map[string]interface{})

    t := v.Type()

    for i := 0; i < t.NumField(); i++ {

        sv := t.Field(i)

        m[sv.Name] = v.Field(i).Interface()

    }

    return m, nil

}

解析文件時指定函數(shù):


t, err := template.New("").Funcs(template.FuncMap{"fields": fields}).ParseFiles("table.gohtml")

if err != nil {

    panic(err)

}

像這樣使用它:


{{range $i, $v :=  .Model}}

<tr>

    {{$m := fields $v}}

    {{range $key, $value := $fields}}

       <td>{{index $m $value}}</td>

    {{end}}

</tr>

{{end}}

在操場上運行它。


另一種方法是編寫一個按名稱查找字段的函數(shù):


func field(s interface{}, k string) (interface{}, error) {

    v := reflect.Indirect(reflect.ValueOf(s))

    if v.Kind() != reflect.Struct {

        return nil, fmt.Errorf("%T is not a struct", s)

    }

    v = v.FieldByName(k)

    if !v.IsValid() {

        return nil, fmt.Errorf("no field in %T with name %s", s, k)

    }

    return v.Interface(), nil

}

用函數(shù)解析:


t, err := template.New("").Funcs(template.FuncMap{"field": field}).ParseFiles("table.gohtml")

像這樣使用它:


{{range $i, $v :=  .Model}}

<tr>

    {{range $key, $value := $fields}}

       <td>{{field $v $value}}</td>

    {{end}}

</tr>

{{end}}

在操場上運行它。


查看完整回答
反對 回復 2022-04-26
  • 1 回答
  • 0 關(guān)注
  • 130 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號