Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang new template not working

Tags:

templates

go

When I run:

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

the page loads fine. But when I try and run

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

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

Does anyone else have this problem?

like image 299
ejones Avatar asked Aug 26 '13 04:08

ejones


1 Answers

The first version works as you expect because the package-level ParseFiles function will return a new template that has the name and content of the first parsed file.

In the second case, though, you're creating a template named "first" and then parsing one with name "index.html". When you call t.Execute on "first", it's still empty.

You can fix the problem by either:

  1. Using template.New("index.html"), so that the file name matches the template name you parse next;
  2. Providing the template name you want to execute explicitly with t.ExecuteTemplate(w, "index.html", nil)
like image 173
Gustavo Niemeyer Avatar answered Nov 05 '22 12:11

Gustavo Niemeyer