init template

This commit is contained in:
andrey1s
2022-10-02 23:31:19 +03:00
parent 3d5d51b2df
commit 621afcc59c
24 changed files with 969 additions and 0 deletions

25
gohtml/engine/engine.go Normal file
View File

@@ -0,0 +1,25 @@
package engine
import (
"fmt"
html "html/template"
"gitoa.ru/go-4devs/mime"
"gitoa.ru/go-4devs/templating/engine"
"gitoa.ru/go-4devs/templating/loader"
)
const Name = "gohtml"
func Parser(source loader.Source) (engine.Template, error) {
tpl, err := html.New(source.Name()).Parse(source.Data())
if err != nil {
return nil, fmt.Errorf("parse html:%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.ExtHTML))...)
}

View File

@@ -0,0 +1,23 @@
package engine_test
import (
"bytes"
"context"
"testing"
"github.com/stretchr/testify/require"
"gitoa.ru/go-4devs/templating/gohtml/engine"
"gitoa.ru/go-4devs/templating/loader"
)
func TestParser(t *testing.T) {
t.Parallel()
ctx := context.Background()
buff := bytes.Buffer{}
tpl, err := engine.Parser(loader.NewSource(t.Name(), `engine:{{.name}}`))
require.NoError(t, err)
require.NoError(t, tpl.Execute(ctx, &buff, map[string]string{"name": "gohtml"}, nil))
require.Equal(t, "engine:gohtml", buff.String())
}

43
gohtml/html.go Normal file
View File

@@ -0,0 +1,43 @@
package gohtml
import (
"context"
"fmt"
html "html/template"
"gitoa.ru/go-4devs/templating"
"gitoa.ru/go-4devs/templating/engine"
gohtml "gitoa.ru/go-4devs/templating/gohtml/engine"
"gitoa.ru/go-4devs/templating/loader"
)
const Name = gohtml.Name
var htm = gohtml.New()
func init() {
templating.AddEngine(htm)
}
// Loader set new loader. This function is not thread-safe.
func Loader(in loader.Loader) {
htm = htm.WithLoader(in)
}
func Must(template *html.Template, err error) {
MustRegister(html.Must(template, err))
}
func MustRegister(template *html.Template) {
if rerr := Register(template); rerr != nil {
panic(rerr)
}
}
func Register(template *html.Template) error {
if err := htm.Add(context.Background(), engine.NewTemplate(template.Name(), template.Execute)); err != nil {
return fmt.Errorf("gohtml loader:%w", err)
}
return nil
}