generated from clevergo/pkg-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrender.go
78 lines (63 loc) · 1.57 KB
/
render.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
// Copyright 2020 CleverGo. All rights reserved.
// Use of this source code is governed by a MIT style license that can be found
// in the LICENSE file.
package jetrenderer
import (
"io"
"sync"
"clevergo.tech/clevergo"
"github.com/CloudyKit/jet/v6"
)
var varsPool sync.Pool
func init() {
varsPool = sync.Pool{
New: func() interface{} {
return jet.VarMap{}
},
}
}
func getVars() (vars jet.VarMap) {
vars, _ = varsPool.Get().(jet.VarMap)
for key := range vars {
delete(vars, key)
}
return
}
func putVars(vars jet.VarMap) {
varsPool.Put(vars)
}
// BeforeRender is a listener that listen the event which trigger before rendering.
type BeforeRender func(w io.Writer, name string, vars jet.VarMap, data interface{}, ctx *clevergo.Context) error
// Renderer implementation of clevergo.Renderer for Jet template engine.
type Renderer struct {
*jet.Set
beforeRender BeforeRender
}
var _ clevergo.Renderer = (*Renderer)(nil)
// New returns a renderer with the given set.
func New(set *jet.Set) *Renderer {
return &Renderer{
Set: set,
}
}
// SetBeforeRender sets before render listener.
func (r *Renderer) SetBeforeRender(fn BeforeRender) {
r.beforeRender = fn
}
// Render implements clevergo.Renderer.Render.
func (r *Renderer) Render(w io.Writer, name string, data interface{}, ctx *clevergo.Context) error {
t, err := r.GetTemplate(name)
if err != nil {
return err
}
vars := getVars()
defer func() {
putVars(vars)
}()
if r.beforeRender != nil {
if err = r.beforeRender(w, name, vars, data, ctx); err != nil {
return err
}
}
return t.Execute(w, vars, data)
}