Go html/template中ParseFiles函数的不同行为

Go html/template中ParseFiles函数的不同行为,go,go-templates,Go,Go Templates,我不明白为什么func(t*Template)Parsefiles(…的行为不同于func Parsefiles(…)。这两个函数都来自“html/Template”包 这将导致以下错误: --- FAIL: TestExecute2 (0.00 seconds) parse_test.go:34: html/template:test: "test" is an incomplete or empty template FAIL exit status 1 请注意,TestExecu

我不明白为什么
func(t*Template)Parsefiles(…
的行为不同于
func Parsefiles(…
)。这两个函数都来自“html/Template”包

这将导致以下错误:

--- FAIL: TestExecute2 (0.00 seconds)
    parse_test.go:34: html/template:test: "test" is an incomplete or empty template
FAIL
exit status 1
请注意,
TestExecute1
通过得很好,因此这不是
template.html
的问题

这是怎么回事?

MakeTemplate2
中缺少什么?

这是因为模板名称。
template
对象可以包含多个teplate,每个teplate都有一个名称。当使用
template.New(“test”)
并执行它时,它将尝试执行一个名为
“test”的模板
在该模板中。但是,
tmpl.ParseFiles
将模板存储到文件名中。这解释了错误消息

如何修复它:

a) 为模板指定正确的名称: 使用

而不是

return template.Must(template.New("test").ParseFiles(path))
b) 指定要在
模板
对象中执行的模板: 使用

而不是

err := tmpl.Execute(ioutil.Discard, "content")

请在

中阅读更多关于这方面的信息,那么为什么
TestExecute1
工作正常?如果我理解您的意思,它将被隐式命名为
template.html
。但是我没有使用
ExecuteTemplate
,它工作得很好。确切地说,名称
template.html
将隐式给出,因此它在对象中执行正确的模板。
return template.Must(template.New("test").ParseFiles(path))
err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")
err := tmpl.Execute(ioutil.Discard, "content")