Home > Back-end >  template.Execute() vs. template.ExecuteTemplate()
template.Execute() vs. template.ExecuteTemplate()

Time:12-31

The following code generated error:

panic: template: body: "body" is an incomplete or empty template
//go:embed resources/*
var res embed.FS

func main() {
    root, _ := fs.Sub(res, "resources")
    t, err := template.New("body").ParseFS(root, "home.html")
    assert(err)
    assert(t.Execute(os.Stdout, nil))
}

the template file resources/home.html is very simple:

{{define "body"}}
Hello World!
{{end}}

If I change the last line of main() to t.ExecuteTemplate(os.Stdout, "body", nil), the problem is gone.

From the library source code, I noticed that the error is because of:

func (t *Template) execute(wr io.Writer, data interface{}) (err error) {
    ... ...
    if t.Tree == nil || t.Root == nil {
        state.errorf("%q is an incomplete or empty template", t.Name())
    }
    ... ...
}

But why t.Tree or t.Root is nil? My go version is:

go version go1.17.5 linux/amd64

CodePudding user response:

I found the problem. VSCode automatcally import text/template for me. This package will not properly parse {{define "..."}} directive.

Use html/template worked OK.

  • Related