I'm very new to Go and try to render an html form template interface.html
which is on the same directory as my hello.go.
The relevant function in hello.go
is:
func UserCreateForm(w http.ResponseWriter, r *http.Request) {
var err error
t := template.New("interface") // Create a template.
t, err = t.ParseFiles("interface.html") // Parse template file.
log.Println(t)
t.Execute(w, t)
log.Println("template rendered")
log.Println(err)
}
When I GET
the url, the template rendered
is logged on terminal but no template is being rendered.
How can I fix this?
UPDATE:
I add log.Println(t)
. It prints out &{<nil> 0xc8200fa0c0 <nil> 0xc8201060a0}
while the html file is clearly there and not empty. Also log.Println(err)
returns <nil>
Well, I realised what caused the problem: When I define the New template, the name in ""
should be same as the one ParseFiles
line.
So one correct whay to do it:
func UserCreateForm(w http.ResponseWriter, r *http.Request) {
var err error
t := template.New("interface.html") // notice .html is added
t, err = t.ParseFiles("interface.html") // Parse template file.
log.Println(t)
t.Execute(w, t)
log.Println("rendering template")
log.Println(err)
}
More elegantly, one can get the template in one line, like:
func UserCreateForm(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("interface.html") // Parse template file.
log.Println(t)
t.Execute(w, t)
log.Println("rendering template")
log.Println(err)
}