Show default content in a template if an object is nil otherwise show based on the set property

{{if not .}}
   output when . is nil or otherwise empty including
     false, 0, and any array, slice, map, or string of length zero
{{else if eq .MetaValue "some-x"}}
       // some-x case
{{else}} 
       // other case
{{end}}

I've been recently facing an issue with identifying nil vs 0 values in a Helm Chart (which uses Go templates, including sprig) and haven't found any solutions posted, so I thought I'd add mine here.

I came up with a kind of ugly solution which is to quote the value and then check for a string that matches "<nil>" (with quotes, so you'd actually be checking (quote .Values.thing | eq "\"<nil>\"")). This allows differentiating tests against empty values vs defined 0 values. In my case, I was trying to build a config file where some default options were non-0, so when 0 was explicitly set, I wanted to know that 0 was set instead of just omitted.

Hopefully this can be a help to someone else.

It would be nice to have a better way to do this, but so far I haven't found anything that doesn't require creating and adding my own template functions.


If you want to ensure you're only checking against nil and not 0, false, the empty string, or any other falsey type, you can use the kindIs function to accomplish this.

{{ if kindIs "invalid" . }} 
   // only if variable is literally nil. falsey values will fallthrough.
{{ else if eq .MetaValue "some-x" }} 
   // other
{{ else }}
   // final case, if any
{{ end }}