template.Execute() vs. template.ExecuteTemplate()

huangapple go评论74阅读模式
英文:

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.Treet.Rootnil 呢?我的 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.

huangapple
  • 本文由 发表于 2021年12月28日 19:25:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/70506364.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定