Home > Software design >  Controlling indents in Go templates
Controlling indents in Go templates

Time:05-28

I have the following Go template:

{{ range $job, $steps := .jobs -}}
    {{ $job -}}:
    {{ range $steps -}}
        {{ . }}
    {{ end }}
{{- end }}

It's producing output that looks like the following:

job1:
    step1
    step2
    job2:  <--- This should not be indented
    step1
    step2

All jobs after job1 are indented four spaces. It's not apparent to me why the template engine would decide to arbitrarily indent the remaining jobs. How can I control indentation so that the output appears as so:

job1:
    step1
    step2
job2:
    step1
    step2

CodePudding user response:

job2's identation does not come from where you think: it comes from the spaces and newline between printing the steps:

{{ range $steps -}}
   {{ . }}  <-- starting from here, and the indentation of the next line
{{ end }}

So the newline and the indentation after step2 of job1 is outputted, and you start job2 right there: already indented.

If you insert newlines and indentation only where you want them in the output, you get what you want:

{{ range $job, $steps := .jobs}}{{ $job }}:{{ range $steps }}
    {{ . }}{{ end }}
{{ end }}

Or format your template the way you want, and disable indentation everywhere, and explicitly output newlines and indentation where you want them:

{{ range $job, $steps := .jobs -}}
    {{- $job -}}:{{"\n"}}
    {{- range $steps -}}
        {{"    "}}{{- . -}}{{"\n"}}
    {{- end -}}
{{- end }}

Or a third solution:

{{ range $job, $steps := .jobs -}}
    {{ $job }}:
    {{- range $steps }}
    {{ . }}{{ end }}
{{ end }}

These all output (try them on the Go Playground):

job1:
    step1
    step2
job2:
    step1
    step2
  • Related