This repository has been archived by the owner on Feb 21, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplates.go
73 lines (64 loc) · 1.87 KB
/
templates.go
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
package main
import (
"fmt"
"html/template"
"net/http"
"path/filepath"
)
// Template data.
type TemplateData struct {
Session map[string]interface{}
SlackRedirectUrl string
}
// HTML templates registry.
// Based on https://hackernoon.com/golang-template-2-template-composition-and-how-to-organize-template-files-4cb40bcdf8f6
type TemplatesRegistry struct {
templatesDir string
templates map[string]*template.Template
}
// Create new templates registry.
func NewTemplatesRegistry(templatesDir string) *TemplatesRegistry {
return &TemplatesRegistry{
templatesDir: templatesDir,
templates: make(map[string]*template.Template),
}
}
// Load templates.
func (r *TemplatesRegistry) LoadTemplates() error {
layoutFiles, err := filepath.Glob(filepath.Join(r.templatesDir, "layouts", "*.html"))
if err != nil {
return err
}
includeFiles, err := filepath.Glob(filepath.Join(r.templatesDir, "*.html"))
if err != nil {
return err
}
mainTemplate := template.New("main")
mainTemplate, err = mainTemplate.Parse(`{{define "main" }} {{ template "base" . }} {{ end }}`)
if err != nil {
return err
}
for _, file := range includeFiles {
fileName := filepath.Base(file)
files := append(layoutFiles, file)
r.templates[fileName], err = mainTemplate.Clone()
if err != nil {
return err
}
r.templates[fileName] = template.Must(r.templates[fileName].ParseFiles(files...))
}
return nil
}
// Render specified template with specified data.
func (r *TemplatesRegistry) RenderTemplate(w http.ResponseWriter, name string, data *TemplateData) {
tmpl, ok := r.templates[name]
if !ok {
http.Error(w, fmt.Sprintf("The template %s does not exist.", name), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := tmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}