简体   繁体   中英

Golang new template not working

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM