我不明白为什么 func (t *Template) Parsefiles(...
与 func ParseFiles(...
的行为不同。这两个函数都来自“html/模板”包。
package example
import (
"html/template"
"io/ioutil"
"testing"
)
func MakeTemplate1(path string) *template.Template {
return template.Must(template.ParseFiles(path))
}
func MakeTemplate2(path string) *template.Template {
return template.Must(template.New("test").ParseFiles(path))
}
func TestExecute1(t *testing.T) {
tmpl := MakeTemplate1("template.html")
err := tmpl.Execute(ioutil.Discard, "content")
if err != nil {
t.Error(err)
}
}
func TestExecute2(t *testing.T) {
tmpl := MakeTemplate2("template.html")
err := tmpl.Execute(ioutil.Discard, "content")
if err != nil {
t.Error(err)
}
}
退出时出现错误:
--- 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
对象可以容纳多个模板,每个模板都有一个名称。当使用 template.New("test")
,然后执行它时,它会尝试在该模板中执行名为 "test"
的模板。但是,tmpl.ParseFiles
将模板存储到文件名中。这解释了错误消息。
如何解决:
a) 为模板指定正确的名称: 使用
return template.Must(template.New("template.html").ParseFiles(path))
代替
return template.Must(template.New("test").ParseFiles(path))
b) 指定要在 Template
对象中执行的模板:
使用
err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")
代替
err := tmpl.Execute(ioutil.Discard, "content")
在 http://golang.org/pkg/text/template/ 中阅读更多相关信息
关于go - html/template 中 ParseFiles 函数的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14747391/