3

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ますか?

4

1 に答える 1

10

テンプレート名が原因です。Templateオブジェクトは複数のteplateを保持でき、それぞれに名前があります。を使用しtemplate.New("test")て実行すると、そのテンプレート内で呼び出されるテンプレートを実行しようとし"test"ます。ただし、tmpl.ParseFilesテンプレートはファイル名で保存されます。それがエラーメッセージの説明です。

それを修正する方法:

a)テンプレートに正しい名前を付けます。

return template.Must(template.New("template.html").ParseFiles(path))

それ以外の

return template.Must(template.New("test").ParseFiles(path))

Templateb)オブジェクトで実行するテンプレートを指定します。

err := tmpl.ExecuteTemplate(ioutil.Discard, "template.html", "content")

それ以外の

err := tmpl.Execute(ioutil.Discard, "content")

詳細については、http://golang.org/pkg/text/template/をご覧ください。

于 2013-02-07T10:39:41.547 に答える