Go can't evaluate field when using range to build from template

邮差的信 提交于 2019-12-24 16:13:59

问题


I have Files slice of File structure in my Go program to keep name and size of files. I created template, see below:

type File struct {
    FileName string
    FileSize int64
}
var Files []File
const tmpl = `
    {{range .Files}}
    file {{.}}
    {{end}}
    `
t := template.Must(template.New("html").Parse(tmplhtml))
    err = t.Execute(os.Stdout, Files)
    if err != nil { panic(err) }

Of course I got panic saying:

can't evaluate field Files in type []main.File

Not sure how to correctly display file names and sizes using range in template.


回答1:


The initial value of your pipeline (the dot) is the value you pass to Template.Execute() which in your case is Files which is of type []File.

So during your template execution the dot . is []File. This slice has no field or method named Files which is what .Files would refer to in your template.

What you should do is simply use . which refers to your slice:

const tmpl = `
    {{range .}}
    file {{.}}
    {{end}}
`

And that's all. Testing it:

var Files []File = []File{
    File{"data.txt", 123},
    File{"prog.txt", 5678},
}
t := template.Must(template.New("html").Parse(tmpl))
err := t.Execute(os.Stdout, Files)

Output (try it on the Go Playground):

file {data.txt 123}

file {prog.txt 5678}


来源:https://stackoverflow.com/questions/37124256/go-cant-evaluate-field-when-using-range-to-build-from-template

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