-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathhtml.go
104 lines (85 loc) · 2.27 KB
/
html.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
package abrenderer
import (
"bytes"
"context"
"fmt"
"html/template"
"path"
"strings"
"github.com/friendsofgo/errors"
"github.com/volatiletech/authboss/v3"
)
// HTML renderer for authboss, renders using html/template
// Allows overrides of the same template names in the same prefixes.
// For example:
// If overridePath is /home/authboss/views
// You could override the login.tpl by creating a file at
// /home/authboss/views/html-templates/login.tpl
type HTML struct {
mountPath string
overridePath string
layout *template.Template
templates map[string]*template.Template
funcMap map[string]interface{}
}
// NewHTML renderer
func NewHTML(mountPath string, overridePath string) *HTML {
h := &HTML{
mountPath: mountPath,
overridePath: overridePath,
templates: make(map[string]*template.Template),
funcMap: template.FuncMap{
"title": strings.Title,
"mountpathed": func(location string) string {
if mountPath == "/" {
return location
}
return path.Join(mountPath, location)
},
},
}
return h
}
// Load a template
func (h *HTML) Load(names ...string) error {
if h.layout == nil {
b, err := loadWithOverride(h.overridePath, "html-templates/layout.tpl")
if err != nil {
return err
}
h.layout, err = template.New("").Funcs(h.funcMap).Parse(string(b))
if err != nil {
return errors.Wrap(err, "failed to load layout template")
}
}
for _, n := range names {
filename := fmt.Sprintf("html-templates/%s.tpl", n)
b, err := loadWithOverride(h.overridePath, filename)
if err != nil {
return err
}
clone, err := h.layout.Clone()
if err != nil {
return err
}
_, err = clone.New("authboss").Funcs(h.funcMap).Parse(string(b))
if err != nil {
return errors.Wrapf(err, "failed to load template for page %s", n)
}
h.templates[n] = clone
}
return nil
}
// Render a view
func (h *HTML) Render(ctx context.Context, page string, data authboss.HTMLData) (output []byte, contentType string, err error) {
buf := &bytes.Buffer{}
tpl, ok := h.templates[page]
if !ok {
return nil, "", errors.Errorf("template for page %s not found", page)
}
err = tpl.Execute(buf, data)
if err != nil {
return nil, "", errors.Wrapf(err, "failed to render template for page %s", page)
}
return buf.Bytes(), "text/html", nil
}