代码拉取完成,页面将自动刷新
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)
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。