New Golang template not working

When I run:

t, _ := template.ParseFiles("index.html") t.Execute(w, nil) 

the page is loading fine. But when I try to run

 t := template.New("first") t, _ = t.ParseFiles("index.html") t.Execute(w, nil) 

the only thing loading is a blank page. I am trying to change the separator values ​​in a Golang html template and would like to make a template, change the separator values, and then parse the file.

Does anyone else have this problem?

+7
go templates
source share
1 answer

The first version works as you expect, because the ParseFiles function at the package level returns a new template with the name and contents of the first parsed file.

In the second case, you create a template named "first" and then parse it with the name "index.html" . When you call t.Execute on "first" , it is still empty.

You can fix the problem either:

  • Using template.New("index.html") so that the file name matches the name of the template, which you then parse;
  • Providing the name of the template that you want to explicitly execute with t.ExecuteTemplate(w, "index.html", nil)
+13
source share

All Articles