cc-backend/templates/templates.go

81 lines
2.3 KiB
Go
Raw Normal View History

2021-12-08 10:09:47 +01:00
package templates
import (
"html/template"
"net/http"
2022-01-17 13:31:40 +01:00
"os"
2022-01-31 15:14:37 +01:00
2022-02-15 10:03:09 +01:00
"github.com/ClusterCockpit/cc-backend/config"
2022-01-31 15:14:37 +01:00
"github.com/ClusterCockpit/cc-backend/log"
2021-12-08 10:09:47 +01:00
)
var templatesDir string
2022-01-17 13:31:40 +01:00
var debugMode bool = os.Getenv("DEBUG") == "1"
var templates map[string]*template.Template = map[string]*template.Template{}
2021-12-08 10:09:47 +01:00
2022-02-15 10:03:09 +01:00
type User struct {
Username string // Username of the currently logged in user
IsAdmin bool
}
2021-12-08 10:09:47 +01:00
type Page struct {
2022-02-15 10:03:09 +01:00
Title string // Page title
Error string // For generic use (e.g. the exact error message on /login)
Info string // For generic use (e.g. "Logout successfull" on /login)
User User // Information about the currently logged in user
Clusters []string // List of all clusters for use in the Header
FilterPresets map[string]interface{} // For pages with the Filter component, this can be used to set initial filters.
Infos map[string]interface{} // For generic use (e.g. username for /monitoring/user/<id>, job id for /monitoring/job/<id>)
Config map[string]interface{} // UI settings for the currently logged in user (e.g. line width, ...)
2021-12-08 10:09:47 +01:00
}
func init() {
bp := "./"
ebp := os.Getenv("BASEPATH")
if ebp != "" {
bp = ebp
}
templatesDir = bp + "templates/"
base := template.Must(template.ParseFiles(templatesDir + "base.tmpl"))
files := []string{
"home.tmpl", "404.tmpl", "login.tmpl",
"imprint.tmpl", "privacy.tmpl",
2022-03-03 14:56:21 +01:00
"config.tmpl",
"monitoring/jobs.tmpl",
"monitoring/job.tmpl",
"monitoring/taglist.tmpl",
"monitoring/list.tmpl",
"monitoring/user.tmpl",
"monitoring/systems.tmpl",
2022-03-24 10:35:52 +01:00
"monitoring/status.tmpl",
"monitoring/node.tmpl",
2022-02-03 10:42:15 +01:00
"monitoring/analysis.tmpl",
}
for _, file := range files {
templates[file] = template.Must(template.Must(base.Clone()).ParseFiles(templatesDir + file))
}
2021-12-08 10:09:47 +01:00
}
func Render(rw http.ResponseWriter, r *http.Request, file string, page *Page) {
t, ok := templates[file]
2021-12-09 16:27:48 +01:00
if !ok {
panic("templates must be predefinied!")
}
if debugMode {
t = template.Must(template.ParseFiles(templatesDir+"base.tmpl", templatesDir+file))
}
2022-02-15 10:03:09 +01:00
if page.Clusters == nil {
for _, c := range config.Clusters {
page.Clusters = append(page.Clusters, c.Name)
}
}
2021-12-09 16:27:48 +01:00
if err := t.Execute(rw, page); err != nil {
2022-01-31 15:14:37 +01:00
log.Errorf("template error: %s", err.Error())
2021-12-08 10:09:47 +01:00
}
}