英文:
Go Template Extra line on the Range
问题
我有以下的Go模板代码:
custom_listeners: {{ range $cl := $.Vars.CustomListeners }}
{{ $cl.ListenerType }}:
{{ range $k,$v := $cl.Values }}{{ $k }}: "{{ $v }}"
{{ end }}{{ end }}
它创建了以下的YAML文件。然而,循环遍历服务时会在服务之间添加额外的空行。我尝试了不同的方法来删除这个空行,但会破坏YAML的格式。
custom_listeners:
service1:
name: "service1"
port: "8091"
ssl_enabled: "false"
<-------------------------- 额外的空行
service2:
name: "service2"
port: "8092"
ssl_enabled: "false"
<-------------------------- 额外的空行
service3:
name: "service3"
port: "9093"
ssl_enabled: "false"
我想知道如何以最佳方式获得以下期望的结果:
custom_listeners:
service1:
name: "service1"
port: "8091"
ssl_enabled: "false"
service2:
name: "service2"
port: "8092"
ssl_enabled: "false"
service3:
name: "service3"
port: "7093"
ssl_enabled: "false"
英文:
I have Following go Template code
custom_listeners: {{ range $cl := $.Vars.CustomListeners }}
{{ $cl.ListenerType }}:
{{ range $k,$v := $cl.Values }}{{ $k }}: "{{ $v }}"
{{ end }}{{ end }}
Which creates the following YAML file . However the looping through the services add extra line between the service. I have tried different method to remove this line but it messes the yml formatting.
custom_listeners:
service1:
name: "service1"
port: "8091"
ssl_enabled: "false"
<-------------------------- Extra Line
service2:
name: "service2"
port: "8092"
ssl_enabled: "false"
<-------------------------- Extra Line
service3:
name: "service3"
port: "9093"
ssl_enabled: "false"
Just wondering what would be the best to way to get Desired result below :
custom_listeners:
service1:
name: "service1"
port: "8091"
ssl_enabled: "false"
service2:
name: "service2"
port: "8092"
ssl_enabled: "false"
service3:
name: "service3"
port: "7093"
ssl_enabled: "false"
答案1
得分: 2
以下是翻译好的内容:
https://pkg.go.dev/text/template#hdr-Text_and_spaces
> ... 如果一个动作的左定界符(默认为“{{”)紧跟着一个减号和空白字符,则所有尾随的空白字符将从前面的文本中删除。类似地,如果右定界符(“}}”)之前有空白字符和减号,则所有前导的空白字符将从后面的文本中删除。...
custom_listeners:
{{- range $cl := $.Vars.CustomListeners }}
{{ $cl.ListenerType }}:
{{- range $k,$v := $cl.Values }}
{{ $k }}: "{{ $v }}"
{{- end }}
{{- end }}
https://go.dev/play/p/aZ7tNqV2Phq
英文:
https://pkg.go.dev/text/template#hdr-Text_and_spaces
> ... if an action's left delimiter (by default "{{") is followed
> immediately by a minus sign and white space, all trailing white space
> is trimmed from the immediately preceding text. Similarly, if the
> right delimiter ("}}") is preceded by white space and a minus sign,
> all leading white space is trimmed from the immediately following
> text. ...
custom_listeners:
{{- range $cl := $.Vars.CustomListeners }}
{{ $cl.ListenerType }}:
{{- range $k,$v := $cl.Values }}
{{ $k }}: "{{ $v }}"
{{- end }}
{{- end }}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论