1 Star 0 Fork 0

h79 / goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
engine.go 1.98 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2022-11-25 01:09 . template
package template
import (
"gitee.com/h79/goutils/common/result"
"io/fs"
"text/template"
)
type Engine struct {
Delims Delims
funcMap template.FuncMap
tmpl *template.Template
}
type Delims struct {
Left string
Right string
}
func DefEngine() *Engine {
return NewEngine(Delims{
Left: "{{",
Right: "}}",
})
}
func NewEngine(delims Delims) *Engine {
return &Engine{
Delims: delims,
funcMap: template.FuncMap{
"jsonEscape": JSONEscape,
"timeCurrent": TimeCurrent,
},
}
}
func (cr *Engine) DelFunc(key string) *Engine {
if _, ok := cr.funcMap[key]; ok {
delete(cr.funcMap, key)
}
return cr
}
func (cr *Engine) AddFunc(key string, value any) *Engine {
cr.funcMap[key] = value
return cr
}
func (cr *Engine) LoadGlob(pattern string) *Engine {
tl := template.New("").
Delims(cr.Delims.Left, cr.Delims.Right).
Funcs(cr.funcMap)
cr.tmpl = template.Must(tl.ParseGlob(pattern))
return cr
}
func (cr *Engine) LoadFiles(files ...string) *Engine {
tl := template.New("").
Delims(cr.Delims.Left, cr.Delims.Right).
Funcs(cr.funcMap)
cr.tmpl = template.Must(tl.ParseFiles(files...))
return cr
}
func (cr *Engine) LoadString(str string) *Engine {
tl := template.New("").
Delims(cr.Delims.Left, cr.Delims.Right).
Funcs(cr.funcMap)
cr.tmpl = template.Must(tl.Parse(str))
return cr
}
func (cr *Engine) LoadFS(fsys fs.FS, patterns ...string) *Engine {
tl := template.New("").
Delims(cr.Delims.Left, cr.Delims.Right).
Funcs(cr.funcMap)
cr.tmpl = template.Must(tl.ParseFS(fsys, patterns...))
return cr
}
func (cr *Engine) OUTPUT(name string, d interface{}) (*Data, error) {
if cr.tmpl == nil {
return nil, result.Error(result.ErrNil, "template object is null")
}
w := &Data{}
if name == "" {
if err := cr.tmpl.Execute(w, d); err != nil {
return nil, result.Error(result.ErrException, err.Error())
}
return w, nil
}
if err := cr.tmpl.ExecuteTemplate(w, name, d); err != nil {
return nil, result.Error(result.ErrException, err.Error())
}
return w, nil
}
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.20.65

搜索帮助