aboutsummaryrefslogtreecommitdiff
path: root/src/server/ui.go
blob: baea7690c5624fa6f9b7355732ecb5f2354f2842 (plain)
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
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)
	}
}