Implementing Template Whitespace Control
1. Understanding Whitespace Behavior
| Construct | Whitespace effect |
|---|---|
{{ x }} | Preserves surrounding whitespace + newline |
{{- x }} | Trims whitespace + newline to the left |
{{ x -}} | Trims whitespace + newline to the right |
{{- x -}} | Trims both sides |
2. Using Left Trim ({{-)
Example: Remove preceding blank line
spec:
replicas: 1
{{- if .Values.extra }}
extra: yes
{{- end }}
3. Using Right Trim (-}})
4. Combining Trim Markers ({{- -}})
| When | Why |
|---|---|
Inside define | Avoid leading/trailing newlines in named templates |
Around if/end | Prevent empty lines in YAML output |
5. Controlling Indentation
| Function | Difference |
|---|---|
indent N | Adds N leading spaces to each line; no leading newline |
nindent N | Same + prepends \n — safe after : |
6. Managing YAML Formatting
7. Using Template Comments ({{/* */}})
| Comment style | Survives render? |
|---|---|
{{/* ... */}} | No — completely stripped |
# yaml comment | Yes — appears in rendered manifest |
8. Avoiding Extra Blank Lines
Example: Compare bad vs good
# BAD — produces blank lines
{{ if .Values.x }}
foo: bar
{{ end }}
# GOOD — trimmed
{{- if .Values.x }}
foo: bar
{{- end }}
9. Formatting Multi-line Strings (| and >)
| Scalar style | Behavior |
|---|---|
| | Literal — preserve newlines |
|- | Literal, strip trailing newline |
|+ | Literal, keep trailing newlines |
> | Folded — newlines become spaces |
>- | Folded, strip trailing newline |
10. Debugging Whitespace Issues
| Tool | Use |
|---|---|
helm template ./chart | Inspect rendered YAML |
helm template ./chart | cat -A | Show invisibles (tabs, EOL) |
helm install --debug --dry-run | Verbose render with values |
yamllint / kubectl apply --dry-run=client | Validate output |