-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgin_templates.go
95 lines (74 loc) · 1.91 KB
/
gin_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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package sfutils
import (
"fmt"
"html/template"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/gin-gonic/gin/render"
"github.com/sirupsen/logrus"
)
type TemplateRender struct {
templates map[string]*template.Template
templatesMutex sync.Mutex
templatesDir string
ext string
debug bool
}
func (r *TemplateRender) Reload() {
r.templatesMutex.Lock()
defer r.templatesMutex.Unlock()
r.templates = map[string]*template.Template{}
}
func (r *TemplateRender) GetTemplate(name string) *template.Template {
r.templatesMutex.Lock()
defer r.templatesMutex.Unlock()
// Check if gin is running in debug mode and load the templates accordingly
tpl := r.templates[name]
if tpl == nil {
tpl = r.loadTemplate(name)
if !r.debug {
r.templates[name] = tpl
}
}
return tpl
}
func (r *TemplateRender) Instance(name string, data interface{}) render.Render {
tpl := r.GetTemplate(name)
return render.HTML{
Template: tpl,
Data: data,
}
}
func (r *TemplateRender) loadTemplate(name string) *template.Template {
// get all templates from includes/
var includes []string
filepath.Walk(path.Join(r.templatesDir, "includes"),
func(path string, f os.FileInfo, err error) error {
if strings.HasSuffix(path, r.ext) {
includes = append(includes, path)
}
return nil
})
// get template
file := path.Join(r.templatesDir, name+r.ext)
//tpl, _ := template.ParseFiles(append([]string{file}, r.Includes...)...)
tpl, err := template.New(path.Base(file)).
Funcs(ginFuncMap).
ParseFiles(append([]string{file}, includes...)...)
if err != nil {
logrus.Errorln("[GIN Template]", fmt.Sprintf("%s: %s", name, err.Error()))
}
return tpl
}
func NewTemplateRender(templatesDir string, ext string, debug bool) *TemplateRender {
r := &TemplateRender{
templates: map[string]*template.Template{},
templatesDir: templatesDir,
ext: ext,
debug: debug,
}
return r
}