douchun1900 2018-02-02 09:39
浏览 50
已采纳

如何通过模板中的变量访问对象字段?

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条回答 默认 最新

  • dqqlziv195281 2018-02-02 11:02
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!