A web blog and personal homepage engine written in Go.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

48 lines
1.2 KiB

package responses
import (
"fmt"
"html/template"
"log"
"net/http"
)
// RenderTemplate renders a Go HTML template.
// The io.Writer can be an http.ResponseWriter.
func RenderTemplate(w http.ResponseWriter, r *http.Request, tmpl string, vars interface{}) error {
if vars == nil {
vars = NewTemplateVars(w, r)
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
// Look for the built-in template.
if b, err := GetFile(tmpl); err == nil {
t, err := template.New(tmpl).Funcs(TemplateFuncs(r)).Parse(string(b))
if err != nil {
log.Printf("bundled template '%s': %s", tmpl, err)
return err
}
// We found the template. Can we find the layout html?
if layout, err := GetFile(".layout.gohtml"); err == nil {
_, err := t.New("layout").Parse(string(layout))
if err != nil {
log.Printf("RenderTemplate(.layout.gohtml): %s", err)
}
} else {
log.Printf("RenderTemplate: .layout.gohtml not found to wrap %s", tmpl)
}
fmt.Printf("Render Templ: %s", tmpl)
if err := t.ExecuteTemplate(w, "layout", vars); err != nil {
log.Printf("RenderTemplate(%s): %s", tmpl, err)
}
log.Println("Done")
return nil
} else {
Panic(w, http.StatusInternalServerError, err.Error())
}
return nil
}