54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package httpapi
|
|
|
|
import (
|
|
"embed"
|
|
"html/template"
|
|
"net/http"
|
|
"path"
|
|
"strings"
|
|
"sync"
|
|
)
|
|
|
|
//go:embed templates/*.tmpl
|
|
var uiFS embed.FS
|
|
|
|
//go:embed static/*
|
|
var staticFS embed.FS
|
|
|
|
var (
|
|
tplOnce sync.Once
|
|
tpl *template.Template
|
|
)
|
|
|
|
func (s *Server) parseTemplatesOnce() {
|
|
tplOnce.Do(func() {
|
|
// Parse all templates under templates/
|
|
t := template.New("base").Funcs(template.FuncMap{})
|
|
t = template.Must(t.ParseFS(uiFS, "templates/*.tmpl"))
|
|
tpl = t
|
|
})
|
|
}
|
|
|
|
func (s *Server) render(w http.ResponseWriter, name string, data map[string]any) {
|
|
s.parseTemplatesOnce()
|
|
if data == nil {
|
|
data = map[string]any{}
|
|
}
|
|
data["Version"] = s.Version
|
|
data["Commit"] = s.Commit
|
|
if s.Commit != "" {
|
|
c := s.Commit
|
|
if len(c) > 12 { c = c[:12] }
|
|
data["CommitShort"] = c
|
|
}
|
|
base := strings.TrimSuffix(path.Base(name), path.Ext(name))
|
|
if base == "dashboard" {
|
|
data["Title"] = "sojuboy"
|
|
} else {
|
|
data["Title"] = strings.Title(base)
|
|
}
|
|
// Tell layout which content template to include
|
|
data["Content"] = base
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
|
_ = tpl.ExecuteTemplate(w, "layout.tmpl", data)
|
|
}
|