red888
red888

Reputation: 31560

How to concatenate variables inside a ternary statement?

I'm trying to do this:

name: {{ $value.enable | ternary $value.prefix $.Release.Namespace $value.suffix $value.override }}

But that syntax is wrong. I can't find any examples for how I would concatenate these vars together: $value.prefix $.Release.Namespace $value.suffix

Edit

I thought I could use print like this:

name: {{ true | ternary (print $value.prefix $.Release.Namespace $value.suffix) $value.fullnameOverride }}

But if you don't specify one of the fields it prints <nil> instead of not printing anything which is what I want.

Upvotes: 2

Views: 1563

Answers (1)

David Maze
David Maze

Reputation: 158917

Helm includes the Sprig template library which includes many useful composable parts.

For the "true" half, you have the three components; you'd like them joined together; but you'd like nil parts to be removed. The Sprig list function constructs a list from arbitrary items; compact takes a list and returns a new list without empty items (either empty string or nil, anything that's a Go zero value); and then join combines the list together into a single string. You can assign that to a temporary variable, and use it in the ternary call:

{{- $qualifiedName := list $value.prefix $.Release.Namespace $value.suffix | compact | join "" }}
name: {{ $value.enable | ternary $qualifiedName $value.fullnameOverride }}

I find the ternary syntax a little hard to read (even if it matches the C-style expr ? t : f syntax) and in this context it's not necessary. A helper template that spelled this out could be easier to understand later.

{{-/* 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 $ .) }}

Upvotes: 2

Related Questions