-
Notifications
You must be signed in to change notification settings - Fork 127
/
templates.go
72 lines (64 loc) · 1.55 KB
/
templates.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
package server
import (
"bytes"
"io"
"log"
"net/http"
"path"
"text/template"
"github.com/dagu-dev/dagu/internal/config"
"github.com/dagu-dev/dagu/internal/constants"
)
var (
// templatePath is the path to the templates directory.
templatePath = "templates/"
)
func (svr *Server) useTemplate(layout string, name string) func(http.ResponseWriter, interface{}) {
files := append(baseTemplates(), path.Join(templatePath, layout))
tmpl, err := template.New(name).Funcs(defaultFunctions()).ParseFS(svr.assets, files...)
if err != nil {
panic(err)
}
return func(w http.ResponseWriter, data interface{}) {
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "base", data); err != nil {
log.Printf("ERR: %v\n", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, &buf)
}
}
func defaultFunctions() template.FuncMap {
cfg := config.Get()
return template.FuncMap{
"defTitle": func(ip interface{}) string {
v, ok := ip.(string)
if !ok || (ok && v == "") {
return ""
}
return v
},
"version": func() string {
return constants.Version
},
"navbarColor": func() string {
return cfg.NavbarColor
},
"navbarTitle": func() string {
return cfg.NavbarTitle
},
"apiURL": func() string {
return cfg.GetAPIBaseURL()
},
}
}
func baseTemplates() []string {
var templateFiles = []string{"base.gohtml"}
ret := make([]string, 0, len(templateFiles))
for _, t := range templateFiles {
ret = append(ret, path.Join(templatePath, t))
}
return ret
}