Implementing Template Whitespace Control

1. Understanding Whitespace Behavior

ConstructWhitespace 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 (-}})

Example: Inline rendering

name: {{ .Values.name -}}
-suffix

4. Combining Trim Markers ({{- -}})

WhenWhy
Inside defineAvoid leading/trailing newlines in named templates
Around if/endPrevent empty lines in YAML output

5. Controlling Indentation

FunctionDifference
indent NAdds N leading spaces to each line; no leading newline
nindent NSame + prepends \n — safe after :

6. Managing YAML Formatting

Example: toYaml with nindent

resources:
  {{- toYaml .Values.resources | nindent 2 }}

7. Using Template Comments ({{/* */}})

Comment styleSurvives render?
{{/* ... */}}No — completely stripped
# yaml commentYes — 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 styleBehavior
|Literal — preserve newlines
|-Literal, strip trailing newline
|+Literal, keep trailing newlines
>Folded — newlines become spaces
>-Folded, strip trailing newline

10. Debugging Whitespace Issues

ToolUse
helm template ./chartInspect rendered YAML
helm template ./chart | cat -AShow invisibles (tabs, EOL)
helm install --debug --dry-runVerbose render with values
yamllint / kubectl apply --dry-run=clientValidate output