通过Go模板中的名称访问结构成员

问题描述 投票:0回答:1

我希望创建一个通用/通用的Go html模板,该模板将根据其输入生成标准的html表。我曾希望按名称查找struct成员,但我无法完成这项工作。

我环顾四周,找不到解决方案,因此我遗漏了一些明显的内容,或者方法错误。在这方面,我会接受一种解决方案,该解决方案显示了一种替代方法或更好的方法,可以避免尝试这种查找。

示例模板:

{{ $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>

示例转到:

package main

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)
    }
}

我希望可以清楚地知道我要做什么-有一个模板,可以在各种类型的结构中重复使用。

我希望创建一个通用/通用的Go html模板,该模板将根据其输入生成标准的html表。我曾希望按名称查找结构成员,但是我无法创建...

templates go go-templates
1个回答
1
投票

创建一个模板函数,将结构字段名称和值作为映射返回:

© www.soinside.com 2019 - 2024. All rights reserved.