forked from jiaoge/sjet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sjet.go
61 lines (47 loc) · 1.26 KB
/
sjet.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
package sjet
import (
"net/http"
"github.com/CloudyKit/jet/v6"
"github.com/gin-gonic/gin"
"github.com/shoppehub/sjet/context"
"github.com/shoppehub/sjet/engine"
"github.com/shoppehub/sjet/function"
)
var customFunc = make(map[string]CustomFunc)
// 创建文件路径的模板引擎
func CreateWithFile(dir string) *engine.TemplateEngine {
e := engine.CreateWithFile(dir)
function.InitGlobalFunc(e)
return e
}
// 创建内存存储的模板引擎
func CreateWithMem() *engine.TemplateEngine {
e := engine.CreateWithMem()
function.InitGlobalFunc(e)
return e
}
func RenderHTMLTemplate(eng *engine.TemplateEngine, c *gin.Context) {
templateContext := context.InitTemplateContext(eng, c)
err := templateContext.FindTemplate(eng)
if err != nil {
c.JSON(http.StatusNotFound, gin.H{
"err": err.Error(),
})
return
}
for key, v := range customFunc {
templateContext.Vars.SetFunc(key, v(c))
}
c.Status(200)
c.Header("Content-Type", "text/html; charset=utf-8")
err = templateContext.Template.Execute(c.Writer, *templateContext.Vars, nil)
if err != nil {
c.Writer.WriteString(err.Error())
return
}
}
type CustomFunc func(c *gin.Context) jet.Func
// 注册自定义的函数
func RegCustomFunc(funcName string, v CustomFunc) {
customFunc[funcName] = v
}