Saturday, 15 March 2014

go - Differing behaviors for ParseFiles functions in html/template -



go - Differing behaviors for ParseFiles functions in html/template -

i don't understand why behaviors of func (t *template) parsefiles(... differs func parsefiles(.... both functions "html/template" package.

package illustration import ( "html/template" "io/ioutil" "testing" ) func maketemplate1(path string) *template.template { homecoming template.must(template.parsefiles(path)) } func maketemplate2(path string) *template.template { homecoming 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 error:

--- fail: testexecute2 (0.00 seconds) parse_test.go:34: html/template:test: "test" incomplete or empty template fail exit status 1

note testexecute1 passed fine not problem template.html.

what's going on here? missing in maketemplate2?

it's because of template names. template objects can hold multiple teplates, each has name. when using template.new("test"), , executing it, seek execute template called "test" within template. however, tmpl.parsefiles stores template name of file. explains error message.

how prepare it:

a) give template right name: use

return template.must(template.new("template.html").parsefiles(path))

instead of

return template.must(template.new("test").parsefiles(path))

b) specify, template want execute in template object: use

err := tmpl.executetemplate(ioutil.discard, "template.html", "content")

instead of

err := tmpl.execute(ioutil.discard, "content")

read more in http://golang.org/pkg/text/template/

go go-templates

No comments:

Post a Comment