deft_code
deft_code

Reputation: 59337

Differing behaviors for ParseFiles functions in html/template

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?

Upvotes: 3

Views: 752

Answers (1)

keks
keks

Reputation: 1052

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/

Upvotes: 10

Related Questions