英文:
Differing behaviors for ParseFiles functions in html/template
问题
我不明白为什么func (t *Template) Parsefiles(...的行为与func ParseFiles(...不同。这两个函数都来自于“html/template”包。
这里发生了什么?
在MakeTemplate2中我漏掉了什么?
英文:
I don't understand why the behaviors of func (t *Template) Parsefiles(... differs from func ParseFiles(.... Both functions are from the "html/template" package.
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)
}
}
This exits with the error:
--- FAIL: TestExecute2 (0.00 seconds)
parse_test.go:34: html/template:test: "test" is an incomplete or empty template
FAIL
exit status 1
Note that TestExecute1 passed fine so this not a problem with template.html.
What's going on here?
What am I missing in MakeTemplate2?
答案1
得分: 10
这是因为模板名称的原因。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/中了解更多信息。
英文:
It's because of the template names. Template objects can hold multiple teplates, each has a name. When using template.New("test"), and then Executing it, it will try to execute a template called "test" inside that template. However, tmpl.ParseFiles stores the template to the name of the file. That explains the error message.
How to fix it:
a) Give the template the correct name:
Use
return template.Must(template.New("template.html").ParseFiles(path))
instead of
return template.Must(template.New("test").ParseFiles(path))
b) Specify, which template you want to execute in you Template object:
Use
err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")
instead of
err := tmpl.Execute(ioutil.Discard, "content")
Read more about this in http://golang.org/pkg/text/template/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论