1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-30 06:28:58 +01:00
liquid/template.go
Carolyn Van Slyck 2e107bef29 Expose the template ast
Sometimes a consumer of a template needs to know what objects were used.
In my case, a template can reference secret values from a secret store
vault and instead of passing all possible secrets to the template only
to render two of them, we use the ast to determine which are used and
only retrieve those values from the vault before rendering the template.

Exposing the ast allows us to use the liquid APIs just like normal,
without having to jump through hoops to build the ast ourselves using
the other types exported in this library.

Signed-off-by: Carolyn Van Slyck <me@carolynvanslyck.com>
2022-01-31 16:18:38 -06:00

51 lines
1.3 KiB
Go

package liquid
import (
"bytes"
"github.com/osteele/liquid/parser"
"github.com/osteele/liquid/render"
)
// A Template is a compiled Liquid template. It knows how to evaluate itself within a variable binding environment, to create a rendered byte slice.
//
// Use Engine.ParseTemplate to create a template.
type Template struct {
root render.Node
cfg *render.Config
}
func newTemplate(cfg *render.Config, source []byte, path string, line int) (*Template, SourceError) {
loc := parser.SourceLoc{Pathname: path, LineNo: line}
root, err := cfg.Compile(string(source), loc)
if err != nil {
return nil, err
}
return &Template{root, cfg}, nil
}
// GetRoot returns the root node of the abstract syntax tree (AST) representing
// the parsed template.
func (t *Template) GetRoot() render.Node {
return t.root
}
// Render executes the template with the specified variable bindings.
func (t *Template) Render(vars Bindings) ([]byte, SourceError) {
buf := new(bytes.Buffer)
err := render.Render(t.root, buf, vars, *t.cfg)
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// RenderString is a convenience wrapper for Render, that has string input and output.
func (t *Template) RenderString(b Bindings) (string, SourceError) {
bs, err := t.Render(b)
if err != nil {
return "", err
}
return string(bs), nil
}