package server import ( "html/template" "log" "net/http" "path/filepath" "strings" "gitlab.com/alexkavon/newsstand/src/conf" ) 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, pageName string, data interface{}) { 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, pageName, templateName, data) } func (ui *Ui) RenderTemplate(w http.ResponseWriter, pageName, templateName string, data interface{}) { p := ui.pages[pageName] err := p.ExecuteTemplate(w, templateName, data) if err != nil { log.Fatal(err) } }