1

indexHandler works perfect! writeHandler - returs me blank page. Templates are the same. Can't understand what's the problem. Please check code bellow

func indexHandler(w http.ResponseWriter, r *http.Request) {
    t, err := template.ParseFiles("templates/index.html", "templates/header.html", "templates/footer.html")
    if err != nil {
        fmt.Fprintf(w, err.Error())
    }
    t.ExecuteTemplate(w, "index", nil)
}

func writeHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf((w), "write")

    t, err := template.ParseFiles("templates/write.html", "templates/header.html", "templates/footer.html")
    if err != nil {
        fmt.Fprintf(w, err.Error())
    }

    t.ExecuteTemplate(w, "write", nil)
}

func main() {
    http.HandleFunc("/", indexHandler)
    http.HandleFunc("/write", writeHandler)
    http.ListenAndServe(":3000", nil)
}

write.html look's like

{{ define "write" }}

{{ template "header" }}

<h1>It works!</h1>

{{ template "footer" }}

{{ end }}

header:

{{ define "header" }}
<!DOCTYPE html>
<html>
<head>
<body>
<h1>HEADER</h1>
{{ end }}

footer:

{{ define "footer" }}
</body>
</html>
{{ end }}

source tree:

templates
---header.html
---index.html
---footer.html
---write.html
Markus W Mahlberg
  • 19,711
  • 6
  • 65
  • 89
Ya Boobey
  • 11
  • 2
  • 2
    Your folder name is `template` but your refer to files like `"templates/xxx"` (note the plural `"s"`). But don't ever parse templates in the handler function, see this for more details: [It takes too much time when using “template” package to generate a dynamic web page to client in golang](http://stackoverflow.com/questions/28451675/it-takes-too-much-time-when-using-template-package-to-generate-a-dynamic-web-p). Also `Execute()` returns an error, please check the returned error! – icza Dec 05 '15 at 12:01
  • sorry, actually it's **templetes**. it's not the reason of a problem. – Ya Boobey Dec 05 '15 at 12:05
  • Please show header and footer. – Markus W Mahlberg Dec 05 '15 at 12:09
  • @Markus W Mahlberg updated – Ya Boobey Dec 05 '15 at 12:16
  • Hm, in writeHandler, `fmt.Fprintf((w), "write")` looks odd to me. Will check that. – Markus W Mahlberg Dec 05 '15 at 12:57
  • Can't reproduce here, it works for me. Do what @icza said, check the error returned by t.ExecuteTemplate https://golang.org/pkg/html/template/#Template.ExecuteTemplate – HectorJ Dec 05 '15 at 15:41
  • I commented out fmt.Fprintf((w), "write") and got the result I think you're after. – Snowman Dec 05 '15 at 22:58
  • @Snowman Thanks, relieves me from that. ;) – Markus W Mahlberg Dec 06 '15 at 05:49
  • @MarkusWMahlberg so was this solved or? – Datsik Dec 06 '15 at 15:42

0 Answers0