/
templater.go
93 lines (85 loc) · 2.5 KB
/
templater.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
package templater
import (
"fmt"
"log"
"net/http"
"text/template"
"bytes"
"github.com/oxtoacart/bpool"
"diserve.didactia.org/lib/env"
)
// Templater struct to hold the loaded templates.
type Templater struct {
templates *template.Template
bufpool *bpool.BufferPool
path string
}
// Render will render the template of the given name, with the given data, to the given response writer.
// Will render an error message to the http.ResponseWriter if template is not found.
// Setting LOADTMPLONREQUEST to true in the environment variables will cause templates to be reloaded on all template renders.
func (t *Templater) Render(w http.ResponseWriter, name string, data interface{}) {
var err error
if env.Vars.LOADTMPLONREQUEST {
t.templates, err = template.ParseGlob(t.path)
if err != nil {
http.Error(w, fmt.Sprint(err), http.StatusInternalServerError)
return
}
}
tmpl := t.templates.Lookup(name)
if tmpl == nil {
http.Error(w, fmt.Sprintf("The template %s does not exist.", name),
http.StatusInternalServerError)
return
}
tmpl.Execute(w, data)
}
// RenderString renders template with name and data, and returns the rendered string.
func (t *Templater) RenderString(name string, data interface{}) (string, error) {
var err error
if env.Vars.LOADTMPLONREQUEST {
t.templates, err = template.ParseGlob(t.path)
if err != nil {
return "", err
}
}
tmpl := t.templates.Lookup(name)
if tmpl == nil {
return "", fmt.Errorf("the template %s does not exist", name)
}
buf := t.bufpool.Get()
tmpl.Execute(buf, data)
str := buf.String()
t.bufpool.Put(buf)
return str, nil
}
// RenderBuffer renders the template of the given name, with the given data, to the given byte buffer
func (t *Templater) RenderBuffer(buf *bytes.Buffer, name string, data interface{}) (error) {
var err error
if env.Vars.LOADTMPLONREQUEST {
t.templates, err = template.ParseGlob(t.path)
if err != nil {
return err
}
}
tmpl := t.templates.Lookup(name)
if tmpl == nil {
return fmt.Errorf("the template %s does not exist", name)
}
tmpl.Execute(buf, data)
return nil
}
// NewTemplater returns a Templater with parsed templates in the directory TMPLPATH.
func NewTemplater(path string) *Templater {
tmpls, err := template.ParseGlob(path)
if err != nil {
log.Fatal(err)
}
bufpool := bpool.NewBufferPool(env.Vars.TMPLBPOOLSIZE)
templater := &Templater{
templates: tmpls,
bufpool: bufpool,
path: path,
}
return templater
}