/
template.go
228 lines (190 loc) · 4.59 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
package render
import (
"bytes"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"sync"
"time"
"github.com/dustin/go-humanize"
"github.com/phogolabs/parcello"
"github.com/tdewolff/minify"
"github.com/tdewolff/minify/css"
"github.com/tdewolff/minify/html"
)
// runtime minifier
var minifier = func() (minifier *minify.M) {
minifier = minify.New()
minifier.AddFunc("text/css", css.Minify)
minifier.AddFunc("text/html", html.Minify)
return
}()
var globalFns = template.FuncMap{
// htmlTime formats the given time to input date value's format.
"htmlTime": func(t time.Time) string {
return t.Format("2006-01-02T15:04")
},
"unixNano": func(i int64) time.Time {
return time.Unix(0, i)
},
"humanizeSize": func(bytes int64) string {
return humanize.Bytes(uint64(bytes))
},
"humanizeNumber": func(number int) string {
return humanize.Comma(int64(number))
},
"humanizeTime": func(t time.Time) string {
return humanize.Time(t)
},
}
type Component struct {
Template string
Components map[string]Component
Functions template.FuncMap
}
type Page struct {
Template string
Components map[string]Component
Functions template.FuncMap
}
// prepareList is the list of templates to call prepare on.
var prepareList []*Template
func prepareAllTemplates() {
for _, tmpl := range prepareList {
tmpl.prepare()
}
}
func BuildPage(n string, p Page) *Template {
tmpl := &Template{
name: n,
page: p,
}
prepareList = append(prepareList, tmpl)
return tmpl
}
type Template struct {
*template.Template
name string
page Page
once sync.Once
}
func (t *Template) prepare() {
t.once.Do(t.do)
}
func (t *Template) do() {
// Combine all component duplicates.
for _, component := range t.page.Components {
if component.Components != nil {
for n, component := range component.Components {
t.page.Components[n] = component
}
}
}
// Combine all function duplicates.
for _, component := range t.page.Components {
if component.Functions != nil {
// Ensure that we have a parent functions map.
if t.page.Functions == nil {
t.page.Functions = template.FuncMap{}
}
for n, fn := range component.Functions {
// Only set into the map if we don't already have the function.
if _, ok := t.page.Functions[n]; !ok {
t.page.Functions[n] = fn
}
}
}
}
tmpl := template.New(t.name)
tmpl = tmpl.Funcs(globalFns)
tmpl = tmpl.Funcs(t.page.Functions)
tmpl = template.Must(tmpl.Parse(string(read(t.page.Template))))
// Parse all components' HTMLs.
for n, component := range t.page.Components {
tmpl = template.Must(tmpl.Parse(
fmt.Sprintf(
"{{ define \"%s\" }}%s{{ end }}",
n, string(read(component.Template)),
),
))
}
t.Template = tmpl
}
// Render renders the template with the given argument into HTML.
func (t *Template) Render(v interface{}) template.HTML {
t.prepare()
var b bytes.Buffer
if err := t.Execute(&b, v); err != nil {
// TODO
log.Println("Template error:", err)
return template.HTML("oh no")
}
return template.HTML(b.String())
}
var (
componentsPath = []string{"pages/style.css"}
componentsCSS = bytes.Buffer{}
componentModTime = time.Time{}
)
// RegisterCSSFile adds the CSS file to the global CSS file, which can be
// located in /components.css
func RegisterCSSFile(path string) {
componentsPath = append(componentsPath, path)
}
func initializeCSS() {
for _, path := range componentsPath {
f, err := parcello.Open(path)
if err != nil {
log.Fatalln("Failed to open file:", err)
}
defer f.Close()
s, err := f.Stat()
if err != nil {
log.Fatalln("Failed to stat file:", err)
}
if modt := s.ModTime(); modt.After(componentModTime) {
componentModTime = s.ModTime()
}
if err := minifier.Minify("text/css", &componentsCSS, f); err != nil {
log.Panicln("Failed to add minifying CSS:", err)
}
}
}
func componentsCSSHandler(w http.ResponseWriter, r *http.Request) {
http.ServeContent(
w, r, "components.css", componentModTime,
bytes.NewReader(componentsCSS.Bytes()),
)
}
func read(path string) []byte {
f, err := parcello.Open(path)
if err != nil {
log.Fatalln("Failed to open template:", err)
}
b, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalln("Failed to read template:", err)
}
f.Close()
return b
}
var initOnce sync.Once
var index *template.Template
func ensureInit() {
initOnce.Do(func() {
parcello.Manager.Walk(".", func(path string, _ os.FileInfo, _ error) error {
log.Println("Path:", path)
return nil
})
index = template.Must(
template.
New("index").
Parse(string(read("pages/index.html"))),
)
initializeCSS()
prepareAllTemplates()
})
}