以下代码生成错误:
panic: template: body: "body" is an incomplete or empty template//go:embed resources/*
var res embed.FS
func main() {
root, _ := fs.Sub(res, "resources")
t, err := template.New("body").ParseFS(root, "home.html")
assert(err)
assert(t.Execute(os.Stdout, nil))
}模板文件resources/home.html非常简单:
{{define "body"}}
Hello World!
{{end}}如果我将main()的最后一行更改为t.ExecuteTemplate(os.Stdout, "body", nil),那么问题就解决了。
从库源代码中,我注意到错误是因为:
func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
... ...
if t.Tree == nil || t.Root == nil {
state.errorf("%q is an incomplete or empty template", t.Name())
}
... ...
}但是为什么 t.Tree或t.Root是nil?我的围棋版本是:
go version go1.17.5 linux/amd64发布于 2021-12-29 02:31:03
我发现了问题。VSCode自动为我导入text/template。此包不能正确解析{{define "..."}}指令。
使用html/template工作正常。
https://stackoverflow.com/questions/70506364
复制相似问题