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

标签 go go-templates

我不明白为什么 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/

相关文章:

json - 在自定义结构标记中使用空格解码 Json

go - 如何检查 []byte 是否全为零

kubernetes - 如何将动态参数传递给运行作业的 Helm chart

go - 雨果没有按修改日期排序帖子

if-statement - 如何在HTML属性中插入if语句?

mysql - UPDATE SQL 命令不适用于 GO 语言

用于遍历 map 的 Golang 不会返回不一致的值

docker - 戈兰 : Is it safe to say that if a struct implements a method then it satisfies all interfaces that define that method's signature?

javascript - 将 Go 函数传递给 html/js 按钮 "onclick"响应

string - 文本/模板如何确定 map 的 "default textual representation"?