-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.go
58 lines (49 loc) · 1.33 KB
/
template.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
package kyuu
import (
"bytes"
"context"
"html/template"
"io/fs"
)
type TemplateEngine interface {
// Render 渲染页面
// data 是渲染页面所需要的数据
Render(ctx context.Context, tplName string, data any) ([]byte, error)
}
var _ TemplateEngine = (*GoTemplateEngine)(nil)
type GoTemplateEngine struct {
T *template.Template
// 也可以考虑设计为 map[string]*template.Template
// 但是其实没太大必要,因为 template.Template 本身就提供了按名索引的功能
}
// Render
// 渲染页面
//
// @Description:
// @receiver g
// @param ctx
// @param tplName
// @param data
// @return []byte
// @return error
func (g *GoTemplateEngine) Render(ctx context.Context, tplName string, data any) ([]byte, error) {
res := &bytes.Buffer{}
err := g.T.ExecuteTemplate(res, tplName, data)
return res.Bytes(), err
}
// 以下这三个方法,可以加可以不加,看你是什么风格的设计者
func (g *GoTemplateEngine) LoadFromGlob(pattern string) error {
var err error
g.T, err = template.ParseGlob(pattern)
return err
}
func (g *GoTemplateEngine) LoadFromFiles(filenames ...string) error {
var err error
g.T, err = template.ParseFiles(filenames...)
return err
}
func (g *GoTemplateEngine) LoadFromFS(fs fs.FS, patterns ...string) error {
var err error
g.T, err = template.ParseFS(fs, patterns...)
return err
}