在html/template中,ParseFiles函数的行为有所不同。

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

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/

huangapple
  • 本文由 发表于 2013年2月7日 17:13:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/14747391.html
匿名

发表评论

匿名网友

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

确定