1 Star 0 Fork 0

h79/goutils

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
engine.go 2.63 KB
一键复制 编辑 原始数据 按行查看 历史
huqiuyun 提交于 2024-07-18 13:39 . template
package template
import (
"gitee.com/h79/goutils/common/result"
"io"
"io/fs"
"os"
"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{
"marshal": JSONMarshal,
"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(obj fs.FS, patterns ...string) *Engine {
tl := template.New("").
Delims(cr.Delims.Left, cr.Delims.Right).
Funcs(cr.funcMap)
cr.tmpl = template.Must(tl.ParseFS(obj, 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
}
func Replace(filename string, tempConfing any) (io.Reader, error) {
return replaceTemplate(filename, tempConfing, func(engine *Engine) {})
}
func ReplaceV2(filename string, tempConfing any, engFn func(engine *Engine)) ([]byte, error) {
data, err := replaceTemplate(filename, tempConfing, engFn)
if err != nil {
return nil, err
}
return data.Bytes(), nil
}
func replaceTemplate(filename string, tempConfing any, engFn func(engine *Engine)) (*Data, error) {
bys, err := os.ReadFile(filename)
if err != nil {
return nil, err
}
engine := DefEngine()
engFn(engine)
engine.LoadString(string(bys))
return engine.OUTPUT("", tempConfing)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/h79/goutils.git
git@gitee.com:h79/goutils.git
h79
goutils
goutils
v1.22.21

搜索帮助