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

87 lines
2.3 KiB
Go
Raw Normal View History

2017-06-26 16:36:53 +02:00
/*
Package liquid is a very early-stage pure Go library that implements Shopify Liquid <https://shopify.github.io/liquid> templates.
It's intended for use in for use in https://github.com/osteele/gojekyll.
*/
package liquid
import (
"bytes"
"github.com/osteele/liquid/chunks"
)
2017-06-26 16:36:53 +02:00
// Engine parses template source into renderable text.
//
// In the future, it will be configured with additional tags, filters, and the {%include%} search path.
type Engine interface {
2017-06-26 16:36:53 +02:00
Parse(text []byte) (Template, error)
ParseAndRender(text []byte, scope map[string]interface{}) ([]byte, error)
2017-06-26 16:36:53 +02:00
ParseAndRenderString(text string, scope map[string]interface{}) (string, error)
}
2017-06-26 16:36:53 +02:00
// Template renders a template according to scope.
//
// Scope is a map of liquid variable names to objects.
type Template interface {
Render(scope map[string]interface{}) ([]byte, error)
2017-06-26 16:36:53 +02:00
RenderString(scope map[string]interface{}) (string, error)
}
type engine struct{}
type template struct {
2017-06-26 18:41:41 +02:00
ast chunks.ASTNode
}
2017-06-26 16:36:53 +02:00
// NewEngine makes a new engine.
func NewEngine() Engine {
return engine{}
}
func (e engine) Parse(text []byte) (Template, error) {
tokens := chunks.Scan(string(text), "")
ast, err := chunks.Parse(tokens)
if err != nil {
return nil, err
}
return &template{ast}, nil
}
// ParseAndRender parses and then renders the template.
func (e engine) ParseAndRender(text []byte, scope map[string]interface{}) ([]byte, error) {
t, err := e.Parse(text)
if err != nil {
return nil, err
}
return t.Render(scope)
}
2017-06-26 16:36:53 +02:00
// ParseAndRenderString is a convenience wrapper for ParseAndRender, that has string input and output.
func (e engine) ParseAndRenderString(text string, scope map[string]interface{}) (string, error) {
b, err := e.ParseAndRender([]byte(text), scope)
if err != nil {
return "", err
}
return string(b), nil
}
2017-06-26 16:36:53 +02:00
// Render applies the template to the scope.
func (t *template) Render(scope map[string]interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
err := t.ast.Render(buf, chunks.Context{scope})
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
2017-06-26 16:36:53 +02:00
// RenderString is a convenience wrapper for Render, that has string input and output.
func (t *template) RenderString(scope map[string]interface{}) (string, error) {
b, err := t.Render(scope)
if err != nil {
return "", err
}
return string(b), nil
}