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

79 lines
2.0 KiB
Go
Raw Normal View History

package liquid
import (
"fmt"
2017-06-27 13:43:42 +02:00
"io"
"github.com/osteele/liquid/chunks"
"github.com/osteele/liquid/expressions"
2017-06-27 18:06:24 +02:00
"github.com/osteele/liquid/filters"
"github.com/osteele/liquid/tags"
)
2017-06-27 18:06:24 +02:00
// TODO move the filters and tags from globals to the engine
func init() {
tags.DefineStandardTags()
filters.DefineStandardFilters()
}
type engine struct{}
type template struct {
2017-06-26 18:41:41 +02:00
ast chunks.ASTNode
}
2017-06-29 19:08:25 +02:00
// NewEngine returns a new template engine.
func NewEngine() Engine {
return engine{}
}
// DefineStartTag is in the Engine interface.
func (e engine) DefineStartTag(name string, td TagDefinition) {
2017-06-30 20:51:21 +02:00
chunks.DefineStartTag(name).Parser(func(c chunks.ASTControlTag) (func(io.Writer, chunks.RenderContext) error, error) {
return func(io.Writer, chunks.RenderContext) error {
fmt.Println("unimplemented tag:", name)
return nil
}, nil
})
}
2017-06-29 19:08:25 +02:00
// DefineFilter is in the Engine interface.
func (e engine) DefineFilter(name string, fn interface{}) {
// TODO define this on the engine, not globally
expressions.DefineFilter(name, fn)
}
2017-06-29 19:08:25 +02:00
// ParseAndRenderString is in the Engine interface.
func (e engine) DefineTag(name string, td TagDefinition) {
// TODO define this on the engine, not globally
2017-06-27 13:43:42 +02:00
chunks.DefineTag(name, chunks.TagDefinition(td))
}
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) {
tokens := chunks.Scan(string(text), "")
ast, err := chunks.Parse(tokens)
if err != nil {
return nil, err
}
return &template{ast}, nil
}
2017-06-29 19:08:25 +02:00
// ParseAndRender is in the Engine interface.
2017-06-29 02:49:38 +02:00
func (e engine) ParseAndRender(text []byte, bindings map[string]interface{}) ([]byte, error) {
2017-06-26 21:36:05 +02:00
t, err := e.ParseTemplate(text)
if err != nil {
return nil, err
}
2017-06-29 02:49:38 +02:00
return t.Render(bindings)
}
2017-06-29 19:08:25 +02:00
// ParseAndRenderString is in the Engine interface.
2017-06-29 02:49:38 +02:00
func (e engine) ParseAndRenderString(text string, bindings map[string]interface{}) (string, error) {
b, err := e.ParseAndRender([]byte(text), bindings)
2017-06-26 16:36:53 +02:00
if err != nil {
return "", err
}
return string(b), nil
}