diff --git a/docs/flow_control.md b/docs/flow_control.md new file mode 100644 index 00000000..6414640a --- /dev/null +++ b/docs/flow_control.md @@ -0,0 +1,11 @@ +# Flow Control Functions + +## fail + +Unconditionally returns an empty `string` and an `error` with the specified +text. This is useful in scenarios where other conditionals have determined that +template rendering should fail. + +``` +fail "Please accept the end user license agreement" +``` diff --git a/docs/index.md b/docs/index.md index 584b7891..d4420a2d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -13,6 +13,7 @@ The Sprig library provides over 70 template functions for Go's template language - [Dictionaries and Dict Functions](dicts.html): `dict`, `hasKey`, `pluck`, etc. - [Type Conversion Functions](conversion.html): `atoi`, `int64`, `toString`, etc. - [File Path Functions](paths.html): `base`, `dir`, `ext`, `clean`, `isAbs` +- [Flow Control Functions](flow_control.html): `fail` - Advanced Functions - [UUID Functions](uuid.html): `uuidv4` - [OS Functions](os.html): `env`, `expandenv` diff --git a/flow_control_test.go b/flow_control_test.go new file mode 100644 index 00000000..d4e5ebf0 --- /dev/null +++ b/flow_control_test.go @@ -0,0 +1,16 @@ +package sprig + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestFail(t *testing.T) { + const msg = "This is an error!" + tpl := fmt.Sprintf(`{{fail "%s"}}`, msg) + _, err := runRaw(tpl, nil) + assert.Error(t, err) + assert.Contains(t, err.Error(), msg) +} diff --git a/functions.go b/functions.go index 34412bc6..e7b30685 100644 --- a/functions.go +++ b/functions.go @@ -1,6 +1,7 @@ package sprig import ( + "errors" "html/template" "os" "path" @@ -254,4 +255,7 @@ var genericMap = map[string]interface{}{ // SemVer: "semver": semver, "semverCompare": semverCompare, + + // Flow Control: + "fail": func(msg string) (string, error) { return "", errors.New(msg) }, }