如何在三元语句中连接变量?
How to concatenate variables inside a ternary statement?
我正在尝试这样做:
name: {{ $value.enable | ternary $value.prefix $.Release.Namespace $value.suffix $value.override }}
但是那个语法是错误的。我找不到有关如何将这些变量连接在一起的任何示例:$value.prefix $.Release.Namespace $value.suffix
编辑
我想我可以像这样使用打印:
name: {{ true | ternary (print $value.prefix $.Release.Namespace $value.suffix) $value.fullnameOverride }}
但是,如果您不指定其中一个字段,它会打印 <nil>
而不是不打印我想要的任何内容。
Helm 包含 Sprig 模板库,其中包含许多有用的可组合部分。
对于“真实”的一半,您拥有三个组成部分;你希望它们结合在一起;但您希望删除零部分。 Sprig list
函数从任意项构造一个列表; compact
接受一个列表,returns 一个没有空项的新列表(空字符串或 nil,任何 Go 零值);然后 join
将列表组合成一个字符串。您可以将其分配给一个临时变量,并在 ternary
调用中使用它:
{{- $qualifiedName := list $value.prefix $.Release.Namespace $value.suffix | compact | join "" }}
name: {{ $value.enable | ternary $qualifiedName $value.fullnameOverride }}
我发现 ternary
语法有点难以阅读(即使它与 C 风格的 expr ? t : f
语法相匹配)并且在这种情况下没有必要。拼写出来的辅助模板以后可能更容易理解。
{{-/* Generate the name of the thing. Call with a list containing
the top-level Helm object and an item from the values file.
(Indented for readability, the template engine removes all of
the whitespace.) */-}}
{{- define "name" -}}
{{- $top := index . 0 -}}
{{- $value := index . 1 -}}
{{- if $value.enable -}}
{{- with $value.prefix -}}{{- . -}}{{- end -}}
{{- with $top.Release.Namespace -}}{{- . -}}{{- end -}}
{{- with $value.suffix -}}{{- . -}}{{- end -}}
{{- else -}}
{{- $value.fullnameOverride -}}
{{- end -}}
{{- end -}}
name: {{ include "name" (list $ .) }}
我正在尝试这样做:
name: {{ $value.enable | ternary $value.prefix $.Release.Namespace $value.suffix $value.override }}
但是那个语法是错误的。我找不到有关如何将这些变量连接在一起的任何示例:$value.prefix $.Release.Namespace $value.suffix
编辑
我想我可以像这样使用打印:
name: {{ true | ternary (print $value.prefix $.Release.Namespace $value.suffix) $value.fullnameOverride }}
但是,如果您不指定其中一个字段,它会打印 <nil>
而不是不打印我想要的任何内容。
Helm 包含 Sprig 模板库,其中包含许多有用的可组合部分。
对于“真实”的一半,您拥有三个组成部分;你希望它们结合在一起;但您希望删除零部分。 Sprig list
函数从任意项构造一个列表; compact
接受一个列表,returns 一个没有空项的新列表(空字符串或 nil,任何 Go 零值);然后 join
将列表组合成一个字符串。您可以将其分配给一个临时变量,并在 ternary
调用中使用它:
{{- $qualifiedName := list $value.prefix $.Release.Namespace $value.suffix | compact | join "" }}
name: {{ $value.enable | ternary $qualifiedName $value.fullnameOverride }}
我发现 ternary
语法有点难以阅读(即使它与 C 风格的 expr ? t : f
语法相匹配)并且在这种情况下没有必要。拼写出来的辅助模板以后可能更容易理解。
{{-/* Generate the name of the thing. Call with a list containing
the top-level Helm object and an item from the values file.
(Indented for readability, the template engine removes all of
the whitespace.) */-}}
{{- define "name" -}}
{{- $top := index . 0 -}}
{{- $value := index . 1 -}}
{{- if $value.enable -}}
{{- with $value.prefix -}}{{- . -}}{{- end -}}
{{- with $top.Release.Namespace -}}{{- . -}}{{- end -}}
{{- with $value.suffix -}}{{- . -}}{{- end -}}
{{- else -}}
{{- $value.fullnameOverride -}}
{{- end -}}
{{- end -}}
name: {{ include "name" (list $ .) }}