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

馋奶兔 提交于 2019-12-05 10:31:38
{{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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!