-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
44 lines (37 loc) · 991 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
package main
import (
"net/http"
"path/filepath"
"sync"
"html/template"
)
// Template is used to serve HTTP templates
type Template struct {
Files []string
tpl *template.Template
once sync.Once
}
// Execute shows the template on the provided ResponseWriter and passes the provided
// The template will be initialized once
func (t *Template) Execute(w http.ResponseWriter, data map[string]interface{}) {
// Initialize the template
t.once.Do(func() {
// Create an array containing the files with a prepended path
files := []string{}
for _, file := range t.Files {
files = append(files, filepath.Join("templates", file))
}
// Parse the files, pass the error to the ResponseWriter if an error occures
tpl, err := template.ParseFiles(files...)
if err != nil {
w.Write([]byte(err.Error()))
return
}
// Store the parsed template
t.tpl = tpl
})
// Show the template if t.tpl is valid
if t.tpl != nil {
t.tpl.ExecuteTemplate(w, "main", data)
}
}