-
Notifications
You must be signed in to change notification settings - Fork 1
/
templateEngine.go
105 lines (92 loc) · 2.33 KB
/
templateEngine.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package january
import (
"errors"
"fmt"
"github.com/CloudyKit/jet/v6"
"github.com/alexedwards/scs/v2"
"github.com/justinas/nosurf"
"html/template"
"log"
"net/http"
)
type TemplateEngine struct {
TemplateEngine string
RootPath string
Secure bool
Port string
ServerName string
JetViews *jet.Set
Session *scs.SessionManager
}
type TemplateData struct {
IsAuthenticated bool
IntMap map[string]int
StringMap map[string]string
FloatMap map[string]float32
Data map[string]interface{}
CSRFToken string
Port string
ServerName string
Secure bool
Error string
Flash string
}
func (t *TemplateEngine) defaultData(td *TemplateData, r *http.Request) *TemplateData {
td.Secure = t.Secure
td.ServerName = t.ServerName
td.Port = t.Port
td.CSRFToken = nosurf.Token(r)
if t.Session.Exists(r.Context(), "userID") {
td.IsAuthenticated = true
}
td.Error = t.Session.PopString(r.Context(), "error")
td.Flash = t.Session.PopString(r.Context(), "flash")
return td
}
func (t *TemplateEngine) Page(w http.ResponseWriter, r *http.Request, view string, variables, data interface{}) error {
switch t.TemplateEngine {
case "go":
return t.GoPage(w, r, view, data)
case "jet":
return t.JetPage(w, r, view, variables, data)
default:
}
return errors.New("no template engine specified")
}
func (t *TemplateEngine) GoPage(w http.ResponseWriter, r *http.Request, view string, data interface{}) error {
tmpl, err := template.ParseFiles(fmt.Sprintf("%s/views/%s.page.tmpl", t.RootPath, view))
if err != nil {
return err
}
td := &TemplateData{}
if data != nil {
td = data.(*TemplateData)
}
if err = tmpl.Execute(w, &td); err != nil {
return err
}
return nil
}
func (t *TemplateEngine) JetPage(w http.ResponseWriter, r *http.Request, templateName string, variables, data interface{}) error {
var vars jet.VarMap
if variables == nil {
vars = make(jet.VarMap)
} else {
vars = variables.(jet.VarMap)
}
td := &TemplateData{}
if data != nil {
td = data.(*TemplateData)
}
td = t.defaultData(td, r)
tmpl, err := t.JetViews.GetTemplate(fmt.Sprintf("%s.html", templateName))
if err != nil {
log.Println(err)
return err
}
if err = tmpl.Execute(w, vars, td); err != nil {
log.Println(err)
return err
}
return nil
}