...
1
2
3
4
5 package render
6
7 import (
8 "html/template"
9 "net/http"
10 )
11
12
13 type Delims struct {
14
15 Left string
16
17 Right string
18 }
19
20
21 type HTMLRender interface {
22
23 Instance(string, any) Render
24 }
25
26
27 type HTMLProduction struct {
28 Template *template.Template
29 Delims Delims
30 }
31
32
33 type HTMLDebug struct {
34 Files []string
35 Glob string
36 Delims Delims
37 FuncMap template.FuncMap
38 }
39
40
41 type HTML struct {
42 Template *template.Template
43 Name string
44 Data any
45 }
46
47 var htmlContentType = []string{"text/html; charset=utf-8"}
48
49
50 func (r HTMLProduction) Instance(name string, data any) Render {
51 return HTML{
52 Template: r.Template,
53 Name: name,
54 Data: data,
55 }
56 }
57
58
59 func (r HTMLDebug) Instance(name string, data any) Render {
60 return HTML{
61 Template: r.loadTemplate(),
62 Name: name,
63 Data: data,
64 }
65 }
66 func (r HTMLDebug) loadTemplate() *template.Template {
67 if r.FuncMap == nil {
68 r.FuncMap = template.FuncMap{}
69 }
70 if len(r.Files) > 0 {
71 return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseFiles(r.Files...))
72 }
73 if r.Glob != "" {
74 return template.Must(template.New("").Delims(r.Delims.Left, r.Delims.Right).Funcs(r.FuncMap).ParseGlob(r.Glob))
75 }
76 panic("the HTML debug render was created without files or glob pattern")
77 }
78
79
80 func (r HTML) Render(w http.ResponseWriter) error {
81 r.WriteContentType(w)
82
83 if r.Name == "" {
84 return r.Template.Execute(w, r.Data)
85 }
86 return r.Template.ExecuteTemplate(w, r.Name, r.Data)
87 }
88
89
90 func (r HTML) WriteContentType(w http.ResponseWriter) {
91 writeContentType(w, htmlContentType)
92 }
93
View as plain text