-
Notifications
You must be signed in to change notification settings - Fork 47
/
template.go
99 lines (76 loc) · 1.64 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
package main
import (
"errors"
"html/template"
"io"
"path/filepath"
"time"
)
var templates map[string]*template.Template
type page struct {
base string
template string
data map[string]interface{}
}
func (p page) toHTML(t string) string {
return t + ".html"
}
func initTemplates() error {
if templates == nil {
templates = make(map[string]*template.Template)
}
templatesDir := "./templates/"
layouts, err := filepath.Glob(templatesDir + "layouts/*.html")
if err != nil {
return err
}
pages, err := filepath.Glob(templatesDir + "pages/*.html")
if err != nil {
return err
}
for _, page := range pages {
files := append(layouts, page)
filename := filepath.Base(page)
var err error
templates[filename], err = template.New(filename).Funcs(template.FuncMap{
"osIcon": osIcon,
"trustHTML": func(s string) template.HTML {
return template.HTML(s)
},
}).ParseFiles(files...)
if err != nil {
return err
}
}
return nil
}
func renderTemplate(w io.Writer, name string, base string, data map[string]interface{}) error {
if templates == nil {
err := initTemplates()
if err != nil {
return err
}
}
t, ok := templates[name]
if !ok {
return errors.New("unable to find template: " + name)
}
if data == nil {
data = make(map[string]interface{})
}
data["BuildDate"] = time.Now()
return t.ExecuteTemplate(w, base, data)
}
func osIcon(platform string) string {
if platform == "Windows" {
return "windows"
} else if platform == "macOS" {
return "apple"
} else if platform == "iOS" {
return "mobile"
} else if platform == "Linux" {
return "linux"
} else {
return "question"
}
}