【问题标题】:Differing behaviors for ParseFiles functions in html/templatehtml/template 中 ParseFiles 函数的不同行为
【发布时间】:2013-02-08 04:47:36
【问题描述】:

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

退出并出现错误:

--- 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 中缺少什么?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    这是因为模板名称。 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/了解更多信息

    【讨论】:

    • 那么为什么TestExecute1 可以正常工作?如果我理解你,它将被赋予template.html 的隐含名称。但我不使用ExecuteTemplate,它工作正常。
    • 没错,名字template.html会被隐式给出,所以它会在对象中执行正确的模板。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多