How do I access object field by variable in template?

半腔热情 提交于 2019-12-24 01:48:06

问题


I have a nested loop:

{{$columns := .columns}}
{{range $dx := .dataList}}
    {{range $c := $columns}}
        {{index $dx $c}}
    {{end}}
{{end}}

dataList is the orm model array. With ID, Title fields , then columns is the []string variable contains all orm model field names like ID, Title.

type AdFile struct {
    ID      uint `gorm:"primary_key"`
    Title   string
}

I've tried with {{(index .listData 0).Title}} and it works.

But if i want to access $dx.Title, $dx.ID .... with Title, ID as variables, but it doesn't work. I've tried $dx[$c].

Can achieve the same thing with Python easily

for i in list_data
    tr
        for p in columns
            td=i[p]

回答1:


To access field values of a struct given by their names, you need help from the reflect package. It can be done like this:

v := AdFile{ID:1, Title: "T1"} // A struct value
name := "ID"                   // field name

fieldValue := reflect.ValueOf(v).FieldByName(name).Interface()

Since this is Go code, you can't embed this in templates. But you may register custom functions with the Template.Funcs() method which may be called from templates.

So let's do this: wrap this functionality into a function, and register it by the name "Field" so we can call it from our template.

func main() {
    t := template.Must(template.New("").Funcs(template.FuncMap{
        "Field": func(v interface{}, name string) interface{} {
            return reflect.ValueOf(v).FieldByName(name).Interface()
        },
    }).Parse(templ))

    m := map[string]interface{}{
        "columns": []string{"ID", "Title"},
        "dataList": []AdFile{
            {ID: 1, Title: "Title1"},
            {ID: 2, Title: "Title2"},
        },
    }

    if err := t.Execute(os.Stdout, m); err != nil {
        panic(err)
    }

}

const templ = `{{$columns := .columns}}
{{range $dx := .dataList}}
    {{range $c := $columns}}
        {{- Field $dx $c }}
    {{end}}
{{end}}`

Output of the above app (try it on the Go Playground):

1
Title1


2
Title2

Note: error check is omitted in the registered "Field" function. You may improve it to return nil if the given field name is invalid, or return an error which is handled by the template engine (in which case template execution would be aborted with the error you return).



来源:https://stackoverflow.com/questions/48579757/how-do-i-access-object-field-by-variable-in-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!