How to trim a string in YAML Go template?

4/16/2020

I have the following values.yaml -

foo:
  - a: bar1
    b: bar2
  - a: bar3 
    b: bar4

I'm using templating as follows -

data:
  string:
{{range .Values.foo}}
  {{ .a ` and ` .b ` or `}}
{{end}}

The output is -

data:
  string: bar1 and bar2 or bar3 and bar4 or

How can I get rid of the trailing or?

-- VBoi
go-templates
kubernetes-helm

1 Answer

4/18/2020

When you iterate over range of a list, you can set local variables to the actual index and value (mirroring Go semantics). So you can change this to put the "or" at the beginning, but skip it on the first time through the loop.

data:
  string:
    {{ range $i, $v := .Values.foo -}}
    {{- if ne $i 0 }} or {{ end -}}
    {{- printf "%s and %s" $v.a $v.b -}}
    {{- end }}
-- David Maze
Source: StackOverflow