-
Notifications
You must be signed in to change notification settings - Fork 0
/
template.go
46 lines (40 loc) · 989 Bytes
/
template.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package views
import (
"fmt"
"html/template"
"io/fs"
"log"
"net/http"
)
type Template struct {
htmlTpl *template.Template
}
func Must(t Template, err error) Template {
if err != nil {
panic(err)
}
return t
}
func ParseFS(fs fs.FS, pattern ...string) (Template, error) {
tpl, err := template.ParseFS(fs, pattern...)
if err != nil {
return Template{}, fmt.Errorf("parsing template: %w", err)
}
return Template{htmlTpl: tpl}, nil
}
func Parse(filename string) (Template, error) {
tpl, err := template.ParseFiles(filename)
if err != nil {
return Template{}, fmt.Errorf("parsing template: %w", err)
}
return Template{htmlTpl: tpl}, nil
}
func (t Template) Execute(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := t.htmlTpl.Execute(w, data)
if err != nil {
log.Printf("executing error: %v", err)
http.Error(w, "There was an error parsing the template", http.StatusInternalServerError)
return
}
}