How to output template data line by line

Viewed 24

I have some data which is a multiline string. And I don't want to modify it. Now I want to prefix each one with a character

{{- define "info.geological" -}}
iWater Well Completion Reports
Anatomy of a Water Well Report
Water table Altitudes
...
{{- end -}}

What I want

data:
  - "iWater Well Completion Reports"
  - "Anatomy of a Water Well Report"
  - "Water table Altitudes"
  ...
2 Answers

Helm's template functions largely come from a library called Sprig. Sprig includes a small number of functions that operate on lists of strings, more specifically including a splitList function.

So, given your multi-line string, you can split it on newlines to get the list of lines

{{- $lines := include "info.geological" . | splitList "\n" -}}

Once you have that list, the easiest way to emit it as a YAML list is the underdocumented toYaml function; so

data:
{{ include "info.geological" . | splitList "\n" | toYaml | indent 2 }}

You can also manually iterate through it with a range loop if you'd like.

data:
{{- $lines := include "info.geological" . | splitList "\n" }}
{{- range $lines }}
  - {{ quote . }}
{{- end }}

Treat it as string in golang, split and print

template

{{- define "info.geological" -}}
iWater Well Completion Reports
Anatomy of a Water Well Report
Water table Altitudes
...
{{- end -}}

template/xxx.yaml

data: 
{{- $dt := include "info.geological" . }}
{{- range ( split "\n" $dt) }}
  - {{ . | quote }}
{{- end }}

output:

data:
  - "iWater Well Completion Reports"
  - "Anatomy of a Water Well Report"
  - "Water table Altitudes"
  ...
Related