I am using go templates to create yaml definitions for kubernetes. I am trying to nest templates but run into issues where I can't re-use a definition simply because the indention is wrong when included. I.e., in one case the contents need indentation but do not in another. How can I control the indention of included content?
Example below. I am reusing pod.tmpl, in the first case it can be included as is. In the second case I need to indent the entire contents so it becomes member of service
{{ if (eq .Case "pod")
# NO indenting
{{ template "pod" }}
{{ end }}
{{ if (eq .Case "service")
service:
# need to indent! so contents become members of service:
{{ template "pod" }}
{{ end }}
You should be able to pipe the output of your template to the indent
function available in the sprig package:
{{ if (eq .Case "service")
service:
# need to indent! so contents become members of service:
{{ template "pod" | indent 4 }}
{{ end }}
I found I can work around the issue if I indent the contents of pod.tmpl and then indent the top portion to align as below
{{ if (eq $template "pod.tmpl") }}
apiVersion: v1
kind: Pod
{{ end }}
{{ if (eq $template "deployment.tmpl") }}
apiVersion: v1
kind: Deployment
metadata:
name: {{ .Name }}-deployment
spec:
replicas: {{ .Scale }}
template:
{{template "pod" dict "Version" $version "Domain" $domain "Image" $image "ImageDerived" $imageDerived "Service" . }}
来源:https://stackoverflow.com/questions/43821989/how-to-indent-content-of-included-template