package server import ( "html/template" "log" "net/http" "path/filepath" "strings" "gitlab.com/alexkavon/newsstand/src/conf" "gitlab.com/alexkavon/newsstand/src/sessions" ) type Ui struct { pages map[string]*template.Template } func NewUi(config *conf.Conf) Ui { return Ui{} } func (ui *Ui) CompilePages(uipath string) { ui.pages = map[string]*template.Template{} baseTmpl, err := template.ParseGlob(filepath.Join(uipath, "templates/*.tmpl.html")) if err != nil { log.Fatal(err) } ui.pages["core"] = baseTmpl pagesDir := filepath.Join(uipath, "pages") tmplGlob := filepath.Join(pagesDir, "**/*.tmpl.html") fileglob, err := filepath.Glob(tmplGlob) if err != nil { log.Fatal(err) } for _, file := range fileglob { f := strings.TrimSuffix(file, ".tmpl.html") tmplName, err := filepath.Rel(pagesDir, f) if err != nil { log.Fatal(err) } skeleton, err := baseTmpl.Clone() if err != nil { log.Fatal(err) } ui.pages[tmplName] = template.Must(skeleton.ParseFiles(file)) log.Println(ui.pages[tmplName].DefinedTemplates()) } } func (ui *Ui) Render(w http.ResponseWriter, r *http.Request, pageName string, data map[string]any) { templateName := "base" // if the pageName has more than 1 `/` then it specifies the name of a template to target slashCount := strings.Count(pageName, "/") if slashCount > 1 { splitName := strings.Split(pageName, "/") templateName = splitName[0] } ui.RenderTemplate(w, r, pageName, templateName, data) } func (ui *Ui) RenderTemplate(w http.ResponseWriter, r *http.Request, pageName, templateName string, data map[string]any) { d := map[string]any{} for k, v := range data { d[k] = v } if session := r.Context().Value(sessions.SessionCtxKey("session")); session != nil { d["session"] = session.(*sessions.Session) } p := ui.pages[pageName] err := p.ExecuteTemplate(w, templateName, d) if err != nil { log.Println(err) } }