1
0
mirror of https://github.com/danog/liquid.git synced 2024-11-26 21:34:44 +01:00
liquid/template.go

57 lines
1.5 KiB
Go
Raw Normal View History

2017-06-27 13:43:42 +02:00
package liquid
import (
"bytes"
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.
//
// Use Engine.ParseTemplate to create a template.
type Template struct {
2017-07-07 11:41:37 +02:00
root render.Node
config *render.Config
2017-06-30 22:13:18 +02:00
}
2017-07-10 17:49:14 +02:00
func newTemplate(cfg *render.Config, source []byte) (*Template, SourceError) {
root, err := cfg.Compile(string(source))
if err != nil {
return nil, err
}
return &Template{root, cfg}, nil
}
// Render executes the template with the specified variable bindings.
func (t *Template) Render(vars Bindings) ([]byte, error) {
2017-06-27 13:43:42 +02:00
buf := new(bytes.Buffer)
2017-07-07 11:41:37 +02:00
err := render.Render(t.root, buf, vars, *t.config)
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.
func (t *Template) RenderString(b Bindings) (string, error) {
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
}
2017-07-04 22:48:38 +02:00
// SetSourcePath sets the filename. This is used for error reporting,
// and as the reference path for relative pathnames in the {% include %} tag.
func (t *Template) SetSourcePath(filename string) {
2017-07-04 22:48:38 +02:00
t.config.Filename = filename
}
2017-07-09 17:49:24 +02:00
// SetSourceLocation sets the source path as SetSourcePath, and also
// the line number of the first line of the template text, for use in
// error reporting.
func (t *Template) SetSourceLocation(filename string, lineNo int) {
2017-07-09 17:49:24 +02:00
t.config.Filename = filename
t.config.LineNo = lineNo
}