如果对象为 nil,则在模板中显示默认内容,否则根据集合显示 属性

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

在我的模板中,我想包含一些默认的 meta 标签(90% 的时间)。但是,当设置了特定的 属性 时,我想显示一组不同的文本。

我知道我可以设置匿名 struct 并使用 "default""some-x" 设置 属性。但是,这意味着,我需要向 90% 当前刚刚通过 nil 的处理程序添加一个匿名结构。

有没有办法做类似的事情

{{if eq . nil}} 
   // default meta tag
{{else if eq .MetaValue "some-x"}} 
   //other
{{end}}

如果我尝试类似我上面的代码,它会编译但不会执行我想要的操作。感谢有关如何在不添加大量样板的情况下正确处理它的任何建议。

谢谢!

{{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}}

我最近遇到了在 Helm Chart(使用 Go 模板,包括 sprig)中识别 nil 与 0 值的问题,并且没有找到任何已发布的解决方案,所以我想我' d 在这里添加我的。

我想出了一种丑陋的解决方案,即引用该值,然后检查匹配“”的字符串(带引号,所以你实际上是在检查(引用 .Values.thing | eq "\"\""))。这允许区分针对空值和定义的 0 值的测试。在我的例子中,我试图构建一个配置文件,其中一些默认选项不是 0,因此当明确设置 0 时,我想知道设置了 0 而不是仅仅省略了。

希望这对其他人有所帮助。

如果有更好的方法来做到这一点会很好,但到目前为止我还没有发现任何不需要创建和添加我自己的模板函数的东西。

如果您想确保只检查 nil 而不是 0false、空字符串或任何其他错误类型,您可以使用 the kindIs function 完成这个。

{{ 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 }}