英文:
Controlling indents in Go templates
问题
我有以下的Go模板:
{{ range $job, $steps := .jobs -}}
{{ $job -}}:
{{ range $steps -}}
{{ . }}
{{ end }}
{{- end }}
它生成的输出如下所示:
job1:
step1
step2
job2: <--- 这里不应该缩进
step1
step2
在job1
之后的所有作业都缩进了四个空格。我不明白为什么模板引擎会随意缩进剩余的作业。我该如何控制缩进,使输出显示如下:
job1:
step1
step2
job2:
step1
step2
英文:
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
答案1
得分: 2
job2
的缩进并不是来自你认为的地方:它来自打印步骤之间的空格和换行符:
{{ range $steps -}}
{{ . }} <-- 从这里开始,以及下一行的缩进
{{ end }}
因此,在job1
的step2
之后的换行符和缩进被输出,你就从那里开始job2
:已经缩进了。
如果你只在输出中插入想要的换行符和缩进,你就会得到你想要的结果:
{{ range $job, $steps := .jobs}}{{ $job }}:{{ range $steps }}
{{ . }}{{ end }}
{{ end }}
或者按照你想要的方式格式化模板,并在需要的地方禁用缩进,并明确输出换行符和缩进:
{{ range $job, $steps := .jobs -}}
{{- $job -}}:{{"\n"}}
{{- range $steps -}}
{{" "}}{{- . -}}{{"\n"}}
{{- end -}}
{{- end }}
或者第三种解决方案:
{{ range $job, $steps := .jobs -}}
{{ $job }}:
{{- range $steps }}
{{ . }}{{ end }}
{{ end }}
这些都会输出以下结果(在Go Playground上尝试一下):
job1:
step1
step2
job2:
step1
step2
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论