guard/engine/engine.go

103 lines
1.9 KiB
Go
Raw Normal View History

2021-11-24 05:26:38 +00:00
package engine
2021-11-24 04:43:32 +00:00
import (
"bytes"
"html/template"
"io"
"io/fs"
"path/filepath"
)
type Engine struct {
name string
Template *template.Template
}
2021-11-24 05:26:38 +00:00
func New(name string) *Engine {
2021-11-24 04:43:32 +00:00
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
}