2017-06-27 13:43:42 +02:00
|
|
|
package liquid
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
|
2017-07-14 16:38:30 +02:00
|
|
|
"github.com/osteele/liquid/parser"
|
2017-07-04 17:03:18 +02:00
|
|
|
"github.com/osteele/liquid/render"
|
2017-06-27 13:43:42 +02:00
|
|
|
)
|
|
|
|
|
2017-07-10 13:51:51 +02:00
|
|
|
// A Template is a compiled Liquid template. It knows how to evaluate itself within a variable binding environment, to create a rendered byte slice.
|
2017-07-10 15:16:35 +02:00
|
|
|
//
|
|
|
|
// Use Engine.ParseTemplate to create a template.
|
|
|
|
type Template struct {
|
2017-07-14 16:38:30 +02:00
|
|
|
root render.Node
|
|
|
|
cfg *render.Config
|
2017-06-30 22:13:18 +02:00
|
|
|
}
|
|
|
|
|
2017-07-14 16:17:34 +02:00
|
|
|
func newTemplate(cfg *render.Config, source []byte, path string, line int) (*Template, SourceError) {
|
2017-07-14 16:38:30 +02:00
|
|
|
loc := parser.SourceLoc{Pathname: path, LineNo: line}
|
|
|
|
root, err := cfg.Compile(string(source), loc)
|
2017-07-10 17:49:14 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return &Template{root, cfg}, nil
|
|
|
|
}
|
|
|
|
|
2022-01-31 23:18:38 +01:00
|
|
|
// GetRoot returns the root node of the abstract syntax tree (AST) representing
|
|
|
|
// the parsed template.
|
|
|
|
func (t *Template) GetRoot() render.Node {
|
|
|
|
return t.root
|
|
|
|
}
|
|
|
|
|
2017-07-10 15:16:35 +02:00
|
|
|
// Render executes the template with the specified variable bindings.
|
2017-07-10 17:52:14 +02:00
|
|
|
func (t *Template) Render(vars Bindings) ([]byte, SourceError) {
|
2017-06-27 13:43:42 +02:00
|
|
|
buf := new(bytes.Buffer)
|
2017-07-14 16:38:30 +02:00
|
|
|
err := render.Render(t.root, buf, vars, *t.cfg)
|
2017-06-27 13:43:42 +02:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return buf.Bytes(), nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// RenderString is a convenience wrapper for Render, that has string input and output.
|
2017-07-10 17:52:14 +02:00
|
|
|
func (t *Template) RenderString(b Bindings) (string, SourceError) {
|
2017-07-03 03:17:04 +02:00
|
|
|
bs, err := t.Render(b)
|
2017-06-27 13:43:42 +02:00
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2017-07-03 03:17:04 +02:00
|
|
|
return string(bs), nil
|
2017-06-27 13:43:42 +02:00
|
|
|
}
|