使用范围从模板构建时,Go 无法评估字段

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

我的 Go 程序中有 FilesFile 结构来保存文件的名称和大小。我创建了模板,见下文:

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

当然我很恐慌说:

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

不确定如何在模板中使用 range 正确显示文件名和大小。

管道的初始值()是您传递给 Template.Execute() 的值,在您的情况下是 Files 类型[]File.

所以在您的模板执行期间, .[]File。此切片没有名为 Files 的字段或方法,这是 .Files 在您的模板中引用的内容。

你应该做的只是使用 . 来引用你的切片:

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

仅此而已。测试它:

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)

输出(在 Go Playground 上尝试):

file {data.txt 123}

file {prog.txt 5678}