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

def*_*ode 3 go go-templates

我不明白为什么行为func (t *Template) Parsefiles(...不同func ParseFiles(....这两个函数都来自"html/template"包.

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

这退出时出现错误:

--- FAIL: TestExecute2 (0.00 seconds)
    parse_test.go:34: html/template:test: "test" is an incomplete or empty template
FAIL
exit status 1
Run Code Online (Sandbox Code Playgroud)

注意,TestExecute1传递正常,所以这不是一个问题template.html.

这里发生了什么?
我错过了MakeTemplate2什么?

kek*_*eks 10

这是因为模板名称.Template对象可以容纳多个teplates,每个teplates都有一个名称.当使用template.New("test"),然后执行它时,它将尝试执行该模板"test"内部调用的模板.但是,tmpl.ParseFiles将模板存储到文件名中.这解释了错误消息.

如何解决:

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

return template.Must(template.New("template.html").ParseFiles(path))
Run Code Online (Sandbox Code Playgroud)

代替

return template.Must(template.New("test").ParseFiles(path))
Run Code Online (Sandbox Code Playgroud)

b)指定要在Template对象中执行的模板:使用

err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")
Run Code Online (Sandbox Code Playgroud)

代替

err := tmpl.Execute(ioutil.Discard, "content")
Run Code Online (Sandbox Code Playgroud)

http://golang.org/pkg/text/template/中了解更多相关信息