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

iro*_*rom 1 go go-templates

我在Go程序中有Files一些File结构来保存文件的名称和大小.我创建了模板,见下文:

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) }
Run Code Online (Sandbox Code Playgroud)

我当然害怕说:

无法评估[] main.File类型中的字段文件

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

icz*_*cza 5

您的管道(中的初始值)为你传递给值Template.Execute()而你的情况是Files这类型的[]File.

所以在模板执行期间, .[]File.此切片没有名称的字段或方法Files,这.Files将在模板中引用.

你应该做的只是使用.哪个指的是你的切片:

const tmpl = `
    {{range .}}
    file {{.}}
    {{end}}
`
Run Code Online (Sandbox Code Playgroud)

就这样.测试它:

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)
Run Code Online (Sandbox Code Playgroud)

输出(在Go Playground上试试):

file {data.txt 123}

file {prog.txt 5678}
Run Code Online (Sandbox Code Playgroud)