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