1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-30 09:48:59 +01:00
liquid/engine.go

80 lines
2.0 KiB
Go
Raw Normal View History

package liquid
import (
2017-06-27 13:43:42 +02:00
"io"
2017-06-27 18:06:24 +02:00
"github.com/osteele/liquid/filters"
2017-07-04 17:03:18 +02:00
"github.com/osteele/liquid/render"
2017-06-30 22:46:17 +02:00
"github.com/osteele/liquid/tags"
)
2017-07-04 17:08:57 +02:00
type engine struct{ settings render.Config }
2017-06-29 19:08:25 +02:00
// NewEngine returns a new template engine.
func NewEngine() Engine {
2017-07-04 17:08:57 +02:00
e := engine{render.NewConfig()}
2017-07-04 22:48:38 +02:00
filters.AddStandardFilters(e.settings.Config)
2017-06-30 22:46:17 +02:00
tags.AddStandardTags(e.settings)
2017-06-30 22:13:18 +02:00
return e
}
// RegisterBlock is in the Engine interface.
func (e engine) RegisterBlock(name string, td Renderer) {
e.settings.AddBlock(name).Renderer(func(w io.Writer, ctx render.Context) error {
s, err := td(ctx)
if err != nil {
return err
}
_, err = w.Write([]byte(s))
return err
})
}
// RegisterFilter is in the Engine interface.
func (e engine) RegisterFilter(name string, fn interface{}) {
2017-06-30 22:13:18 +02:00
e.settings.AddFilter(name, fn)
}
// RegisterTag is in the Engine interface.
func (e engine) RegisterTag(name string, td Renderer) {
2017-07-01 16:36:47 +02:00
// For simplicity, don't expose the two stage parsing/rendering process to clients.
// Client tags do everything at runtime.
e.settings.AddTag(name, func(_ string) (func(io.Writer, render.Context) error, error) {
return func(w io.Writer, ctx render.Context) error {
s, err := td(ctx)
if err != nil {
return err
}
_, err = w.Write([]byte(s))
return err
}, nil
2017-07-01 16:36:47 +02:00
})
2017-06-27 13:43:42 +02:00
}
2017-06-29 19:08:25 +02:00
// ParseTemplate is in the Engine interface.
2017-06-26 21:36:05 +02:00
func (e engine) ParseTemplate(text []byte) (Template, error) {
2017-06-30 22:51:39 +02:00
ast, err := e.settings.Parse(string(text))
if err != nil {
return nil, err
}
2017-06-30 22:13:18 +02:00
return &template{ast, e.settings}, nil
}
2017-06-29 19:08:25 +02:00
// ParseAndRender is in the Engine interface.
2017-07-03 03:17:04 +02:00
func (e engine) ParseAndRender(text []byte, b Bindings) ([]byte, error) {
2017-06-26 21:36:05 +02:00
t, err := e.ParseTemplate(text)
if err != nil {
return nil, err
}
2017-07-03 03:17:04 +02:00
return t.Render(b)
}
2017-06-29 19:08:25 +02:00
// ParseAndRenderString is in the Engine interface.
2017-07-03 03:17:04 +02:00
func (e engine) ParseAndRenderString(text string, b Bindings) (string, error) {
bs, err := e.ParseAndRender([]byte(text), b)
2017-06-26 16:36:53 +02:00
if err != nil {
return "", err
}
2017-07-03 03:17:04 +02:00
return string(bs), nil
}