From 59a0a530a35d48c843abbf438d4d1f9620add0c9 Mon Sep 17 00:00:00 2001 From: jamslinger Date: Fri, 26 Apr 2024 10:20:34 +0200 Subject: [PATCH] Add FRender to allow rendering into a custom io.Writer --- engine.go | 9 +++++++++ engine_test.go | 21 +++++++++++++++++++++ template.go | 10 ++++++++++ 3 files changed, 40 insertions(+) diff --git a/engine.go b/engine.go index 4258657..c9a2866 100644 --- a/engine.go +++ b/engine.go @@ -98,6 +98,15 @@ func (e *Engine) ParseAndRender(source []byte, b Bindings) ([]byte, SourceError) return tpl.Render(b) } +// ParseAndFRender parses and then renders the template into w. +func (e *Engine) ParseAndFRender(w io.Writer, source []byte, b Bindings) SourceError { + tpl, err := e.ParseTemplate(source) + if err != nil { + return err + } + return tpl.FRender(w, b) +} + // ParseAndRenderString is a convenience wrapper for ParseAndRender, that takes string input and returns a string. func (e *Engine) ParseAndRenderString(source string, b Bindings) (string, SourceError) { bs, err := e.ParseAndRender([]byte(source), b) diff --git a/engine_test.go b/engine_test.go index 573e610..ca7de12 100644 --- a/engine_test.go +++ b/engine_test.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "io" + "strings" "testing" "github.com/stretchr/testify/require" @@ -39,6 +40,26 @@ func TestEngine_ParseAndRenderString(t *testing.T) { } } +type capWriter struct { + bytes.Buffer +} + +func (c *capWriter) Write(bs []byte) (int, error) { + return c.Buffer.Write([]byte(strings.ToUpper(string(bs)))) +} + +func TestEngine_ParseAndFRender(t *testing.T) { + engine := NewEngine() + for i, test := range liquidTests { + t.Run(fmt.Sprint(i+1), func(t *testing.T) { + wr := capWriter{} + err := engine.ParseAndFRender(&wr, []byte(test.in), testBindings) + require.NoErrorf(t, err, test.in) + require.Equalf(t, strings.ToUpper(test.expected), wr.String(), test.in) + }) + } +} + func TestEngine_ParseAndRenderString_ptr_to_hash(t *testing.T) { params := map[string]interface{}{ "message": &map[string]interface{}{ diff --git a/template.go b/template.go index 5e60a90..de88456 100644 --- a/template.go +++ b/template.go @@ -2,6 +2,7 @@ package liquid import ( "bytes" + "io" "github.com/osteele/liquid/parser" "github.com/osteele/liquid/render" @@ -40,6 +41,15 @@ func (t *Template) Render(vars Bindings) ([]byte, SourceError) { return buf.Bytes(), nil } +// FRender executes the template with the specified variable bindings and renders it into w. +func (t *Template) FRender(w io.Writer, vars Bindings) SourceError { + err := render.Render(t.root, w, vars, *t.cfg) + if err != nil { + return err + } + return 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)