-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathtemplates.go
93 lines (84 loc) · 2.3 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
// Copyright (C) 2024 The Dagu Authors
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package server
import (
"bytes"
"io"
"net/http"
"path/filepath"
"text/template"
"github.com/dagu-org/dagu/internal/constants"
)
var (
// templatePath is the path to the templates directory.
templatePath = "templates/"
)
func (srv *Server) useTemplate(
layout string, name string,
) func(http.ResponseWriter, any) {
files := append(baseTemplates(), filepath.Join(templatePath, layout))
tmpl, err := template.New(name).Funcs(
defaultFunctions(srv.funcsConfig)).ParseFS(srv.assets, files...,
)
if err != nil {
panic(err)
}
return func(w http.ResponseWriter, data any) {
var buf bytes.Buffer
if err := tmpl.ExecuteTemplate(&buf, "base", data); err != nil {
srv.logger.Error("Template execution failed", "error", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
_, _ = io.Copy(w, &buf)
}
}
type funcsConfig struct {
NavbarColor string
NavbarTitle string
APIBaseURL string
}
func defaultFunctions(cfg funcsConfig) template.FuncMap {
return template.FuncMap{
"defTitle": func(ip any) 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.APIBaseURL
},
}
}
func baseTemplates() []string {
var templateFiles = []string{"base.gohtml"}
ret := make([]string, 0, len(templateFiles))
for _, t := range templateFiles {
ret = append(ret, filepath.Join(templatePath, t))
}
return ret
}