我的图表目录中有一些 YAML 文件,在我的模板中,我想在数组中使用它们的内容。例如,如果我有 2 个文件:
# file-a.yaml:
name: abc
# file-b.yaml:
name: xyz
我的模板:
{{ printf "files:" | nindent 8 -}}
{{- range $stagesPath, $fileContent := $.Files.Glob (printf "files/*.yaml") }}
- {{ $.Files.Get $stagesPath | toYaml | nindent 10 }}
{{- end }}
会渲染:
files:
-
|
name: abc
-
|
name: xyz
但我想要:
files:
- name: abc
- name: xyz
你能帮我吗? :)
.Files.Get
已经返回一个字符串。当您将其通过 toYaml
传输时,字符串会进行双转义。这可能就是您最终使用 YAML 块标量语法的原因。
由于您已经将文件内容作为字符串,因此不需要
toYaml
。您确实需要 indent
它才能正确地适应包含的 YAML 块语法,但是然后 trim
前导空格,这样第一行就不会过度缩进。
files:
{{- range $stagesPath := $.Files.Glob (printf "files/*.yaml") }}
- {{ $.Files.Get $stagesPath | indent 10 | trim }}
{{- end }}
原则上,您可以使用
fromYaml
将文件内容解析为结构化值。模板语言没有任何类型的 map
函数,因此构建数据值列表然后将其转储出来是很棘手的。这可能有效(读取每个文件,解析它fromYaml
,将每个项目收集到列表中,然后将整个列表放入toYaml
一次):
{{- $files := list }}
{{- range $stagesPath := .Files.Glob "files/*.yaml" }}
{{- $files = append $files ($.Files.Get $stagesPath | fromYaml) }}
{{- end }}
files: {{- $files | toYaml | nindent 10 }}