init template
This commit is contained in:
25
gotxt/engine/engine.go
Normal file
25
gotxt/engine/engine.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package engine
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
text "text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/mime"
|
||||
"gitoa.ru/go-4devs/templating/engine"
|
||||
"gitoa.ru/go-4devs/templating/loader"
|
||||
)
|
||||
|
||||
const Name = "gotxt"
|
||||
|
||||
func Parser(source loader.Source) (engine.Template, error) {
|
||||
tpl, err := text.New(source.Name()).Parse(source.Data())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse text:%w", engine.ErrNotSupport)
|
||||
}
|
||||
|
||||
return engine.NewTemplate(tpl.Name(), tpl.Execute), nil
|
||||
}
|
||||
|
||||
func New(opts ...engine.Option) *engine.Engine {
|
||||
return engine.New(Name, Parser, append(opts, engine.WithFormats(mime.ExtTxt, mime.ExtText))...)
|
||||
}
|
||||
43
gotxt/text.go
Normal file
43
gotxt/text.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package gotxt
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
text "text/template"
|
||||
|
||||
"gitoa.ru/go-4devs/templating"
|
||||
"gitoa.ru/go-4devs/templating/engine"
|
||||
gotxt "gitoa.ru/go-4devs/templating/gotxt/engine"
|
||||
"gitoa.ru/go-4devs/templating/loader"
|
||||
)
|
||||
|
||||
const Name = gotxt.Name
|
||||
|
||||
var txt = gotxt.New()
|
||||
|
||||
func init() {
|
||||
templating.AddEngine(txt)
|
||||
}
|
||||
|
||||
// Loader set new loader. This function is not thread-safe.
|
||||
func Loader(in loader.Loader) {
|
||||
txt = txt.WithLoader(in)
|
||||
}
|
||||
|
||||
func Must(template *text.Template, err error) {
|
||||
MustRegister(text.Must(template, err))
|
||||
}
|
||||
|
||||
func MustRegister(template *text.Template) {
|
||||
if rerr := Register(template); rerr != nil {
|
||||
panic(rerr)
|
||||
}
|
||||
}
|
||||
|
||||
func Register(template *text.Template) error {
|
||||
if err := txt.Add(context.Background(), engine.NewTemplate(template.Name(), template.Execute)); err != nil {
|
||||
return fmt.Errorf("gotext loader:%w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user