Add ExecuteSafe for avoiding partial output if an error occurs

This commit is contained in:
Tyler Sommer 2023-04-07 21:37:32 -06:00
parent d63ce1a09a
commit ea7f7a2e68
No known key found for this signature in database
GPG key ID: C09C010500DBD008
2 changed files with 27 additions and 6 deletions

View file

@ -1,14 +1,12 @@
package stick_test
import (
"fmt"
"os"
"strconv"
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"strconv"
"github.com/tyler-sommer/stick"
)
@ -25,6 +23,18 @@ func ExampleEnv_Execute() {
// Output: Hello, World!
}
// An example of executing a template that avoids writing any output if an error occurs.
func ExampleEnv_ExecuteSafe() {
env := stick.New(nil)
params := map[string]stick.Value{"name": "World"}
err := env.ExecuteSafe(`Hello, {{ 'world' | fakefilter }}!`, os.Stdout, params)
if err != nil {
fmt.Println(err)
}
// Output: Undeclared filter "fakefilter"
}
type exampleType struct{}
func (e exampleType) Boolean() bool {

View file

@ -1,6 +1,7 @@
package stick // import "github.com/tyler-sommer/stick"
import (
"bytes"
"io"
"github.com/tyler-sommer/stick/parse"
@ -104,6 +105,16 @@ func (env *Env) Execute(tpl string, out io.Writer, ctx map[string]Value) error {
return execute(tpl, out, ctx, env)
}
// ExecuteSafe executes the template but does not output anything if an error occurs.
func (env *Env) ExecuteSafe(tpl string, out io.Writer, ctx map[string]Value) error {
buf := &bytes.Buffer{}
if err := env.Execute(tpl, buf, ctx); err != nil {
return err
}
_, err := io.Copy(out, buf)
return err
}
// Parse loads and parses the given template.
func (env *Env) Parse(name string) (*parse.Tree, error) {
return env.load(name)