在Go模板中删除文件开头的换行符。

huangapple go评论78阅读模式
英文:

Remove new line at the beginning of the file - Go template

问题

我正在使用以下循环在Hashicorp Vault中生成凭据文件。一切都正常,但是文件开头有一个空行。我该如何删除它?

vault.hashicorp.com/agent-inject-template-credentials.txt: |
  {{- with secret "secret/data/test/config" }}{{- range $k, $v := .Data.data }}
  {{ $k }}: {{ $v }}
  {{- end }}{{- end }}  

输入:map[test1:test1 test2:test2 test3:test3]

当前输出:

// 开头有一个空行
test1: test1
test2: test2
test3: test3
英文:

I'm using fallowing loop to generate credentials file in Hashicorp Vault. All works well but I'm getting one new line at the beginning of the file. How can I remove it?

vault.hashicorp.com/agent-inject-template-credentials.txt: |
  {{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data }}
  {{ $k }}: {{ $v }}
  {{- end }}{{- end }}

Input: map[test1:test1 test2:test2 test3:test3]

Current output:

// one empty line at the beginning
test1: test1
test2: test2
test3: test3

答案1

得分: 3

你的模板在渲染元素之前包含一个换行符,使用-符号来去掉它:

{{- with secret "secret/data/test/config" }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{- end }}{{- end }}

注意在第一行末尾添加了-符号。

这样当然会将每对键值对都渲染在同一行上。通过从最后一行开头删除-符号,保留在渲染元素之后的换行符:

{{- with secret "secret/data/test/config" }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{ end }}{{- end }}

或者,你可以将第一个添加的-符号移到第二行的开头:

{{- with secret "secret/data/test/config" }}{{- range $k, $v := .Data.data }}
{{- $k }}: {{ $v }}
{{ end }}{{- end }}

这些模板将输出(没有第一行空行):

test1: test1
test2: test2
test3: test3

Go Playground上试一试。

英文:

Your template contains a newline before rendering the elements, use the - sign to get rid of that:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{- end }}{{- end }}

Note the added - sign at the end of the first line.

This of course will render each pair on the same line. Leave the newline at the end of rendering the elements by removing the - sign from the beginning of the last line:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data -}}
{{ $k }}: {{ $v }}
{{ end }}{{- end }}

Alternatively you can move the first added - sign to the beginning of the second line:

{{- with secret (print "secret/data/test/config") }}{{- range $k, $v := .Data.data }}
{{- $k }}: {{ $v }}
{{ end }}{{- end }}

These templates will output (no first empty line):

test1: test1
test2: test2
test3: test3

Try it on the Go Playground.

huangapple
  • 本文由 发表于 2022年9月5日 16:07:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/73606300.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定