44 lines
871 B
Go
44 lines
871 B
Go
package views
|
|
|
|
import (
|
|
"fmt"
|
|
"html/template"
|
|
"io"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
type Template struct {
|
|
htmlTpl *template.Template
|
|
}
|
|
|
|
func (t Template) Execute(w http.ResponseWriter, data interface{}) {
|
|
w.Header().Set("Content-Type", "text/html; charset=utf8")
|
|
err := t.htmlTpl.Execute(w, data)
|
|
if err != nil {
|
|
log.Printf("Error executing template: %v", err)
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|
|
func (t Template) ExecuteWriter(w io.Writer, data interface{}) error {
|
|
return t.htmlTpl.Execute(w, data)
|
|
}
|
|
|
|
func FromFile(filepath string) (Template, error) {
|
|
tpl, err := template.ParseFiles(filepath)
|
|
if err != nil {
|
|
return Template{}, fmt.Errorf("Error parsing template: %v", err)
|
|
}
|
|
return Template{
|
|
htmlTpl: tpl,
|
|
}, nil
|
|
}
|
|
|
|
func Must(t Template, err error) Template {
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return t
|
|
}
|