使用范围从模板构建时,Go无法评估字段 [英] Go can't evaluate field when using range to build from template

查看:41
本文介绍了使用范围从模板构建时,Go无法评估字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Go程序中有 File 结构的 Files 切片,用于保留文件的名称和大小.我创建了模板,请参见下文:

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

我当然很恐慌:

无法评估类型为[] main.File

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

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

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

推荐答案

管道的初始值()是您传递给

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.

因此,在模板执行期间, . [] File .该切片没有名为 Files 的字段或方法,而 .Files 将在模板中引用.

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

仅此而已.测试它:

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)

输出(在游乐场上尝试):

file {data.txt 123}

file {prog.txt 5678}

这篇关于使用范围从模板构建时,Go无法评估字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆