【问题标题】:Go can't evaluate field when using range to build from template使用范围从模板构建时Go无法评估字段
【发布时间】:2016-05-09 19:48:37
【问题描述】:

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

我当然很恐慌:

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

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

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    管道的初始值()是你传递给Template.Execute()的值,在你的例子中是Files,它的类型是[]File

    因此,在您的模板执行期间,dot .[]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}
    

    【讨论】:

      猜你喜欢
      • 2023-03-19
      • 2014-09-30
      • 2021-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多