ksrv/engine/template.go

103 lines
1.9 KiB
Go

package engine
import (
"bytes"
"html/template"
"io"
"io/fs"
"path/filepath"
)
type Engine struct {
name string
Template *template.Template
}
func New(name string) *Engine {
Ename := "E" + name
if Ename == "E" {
Ename = "Engine"
}
return &Engine{Ename, template.New(name)}
}
func (e *Engine) Funcs(funcMap template.FuncMap) *Engine {
e.Template = e.Template.Funcs(funcMap)
return e
}
func (e *Engine) Parse(text string) (*Engine, error) {
tmp, err := e.Template.Parse(text)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseFS(fs fs.FS, patterns ...string) (*Engine, error) {
tmp, err := e.Template.ParseFS(fs, patterns...)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseFiles(filenames ...string) (*Engine, error) {
tmp, err := e.Template.ParseFiles(filenames...)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) ParseGlob(pattern string) (*Engine, error) {
tmp, err := e.Template.ParseGlob(pattern)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func (e *Engine) OverrideGlob(pattern string) (*Engine, error) {
matches, _ := filepath.Glob(pattern)
if len(matches) <= 0 {
// surpass error if no tmpl found
return e, nil
}
tmp, err := e.Template.ParseGlob(pattern)
if err != nil {
return e, err
}
e.Template = tmp
return e, err
}
func Must(e *Engine, err error) *Engine {
if err != nil {
panic(err)
}
return e
}
func (e *Engine) ExecuteTemplate(wr io.Writer, name string, data interface{}) error {
buf := &bytes.Buffer{}
err := e.Template.ExecuteTemplate(buf, name, data)
if err != nil {
return err
}
_, err = wr.Write(buf.Bytes())
return err
}
func (e *Engine) Execute(wr io.Writer, data interface{}) error {
buf := &bytes.Buffer{}
err := e.Template.Execute(buf, data)
if err != nil {
return err
}
_, err = wr.Write(buf.Bytes())
return err
}