example.md
{{< divide x=4 y=0 >}}
layouts/shortcodes/divide.html
{{ if and (isset .Params "y") (eq (.Get "y") 0) }}
{{ errorf "Cannot divide by zero." }}
{{ end }}
{{ div (.Get "x") (.Get "y") }}
console (current behavior)
ERROR 2021/12/14 09:31:46 Cannot divide by zero.
Error: Error building site: “/home/jmooring/code/hugo-testing/content/post/test.md:7:1”: failed to render shortcode “divide”: failed to process shortcode: “/home/jmooring/code/hugo-testing/layouts/shortcodes/divide.html:6:3”: execute of template failed: template: shortcodes/divide.html:6:3: executing “shortcodes/divide.html” at <div (.Get “x”) (.Get “y”)>: error calling div: can’t divide the value by 0
console (what I want)
ERROR 2021/12/14 09:31:46 Cannot divide by zero.
It would be convenient if additional messages were swallowed.
Yes, there are several other ways to accomplish this, but it can get messy when multiple conditions must be met or there are many lines of code.
Wrap the code in else
{{ if and (isset .Params "y") (eq (.Get "y") 0) }}
{{ errorf "Cannot divide by zero." }}
{{ else }}
{{ div (.Get "x") (.Get "y") }}
{{ end }}
Set flag
{{ $err := false }}
{{ if and (isset .Params "y") (eq (.Get "y") 0) }}
{{ $err = true}}
{{ errorf "Cannot divide by zero." }}
{{ end }}
{{ if not $err }}
{{ div (.Get "x") (.Get "y") }}
{{ end }}
Call template
{{ if and (isset .Params "y") (eq (.Get "y") 0) }}
{{ errorf "Cannot divide by zero." }}
{{ else }}
{{ template "divide" (dict "x" (.Get "x") "y" (.Get "y") )}}
{{ end }}
{{ define "divide" }}
{{ div .x .y }}
{{ end }}