英文:
template.Execute() vs. template.ExecuteTemplate()
问题
以下是翻译好的内容:
以下代码生成了错误:
panic: template: body: "body" 是一个不完整或空的模板
//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 版本是:
go version go1.17.5 linux/amd64
英文:
The following code generated error:
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))
}
the template file resources/home.html is very simple:
{{define "body"}}
Hello World!
{{end}}
If I change the last line of main() to t.ExecuteTemplate(os.Stdout, "body", nil), the problem is gone.
From the library source code, I noticed that the error is because of:
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())
	}
    ... ...
}
But why t.Tree or t.Root is nil?  My go version is:
go version go1.17.5 linux/amd64
答案1
得分: 2
我找到了问题。VSCode自动为我导入了text/template。这个包无法正确解析{{define "..."}}指令。
使用html/template可以正常工作。
英文:
I found the problem.  VSCode automatcally import text/template for me.  This package will not properly parse {{define "..."}} directive.
Use html/template worked OK.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论