您不能像您描述的那样真正一起使用 template 和 toYaml 。您可以做的是使用类似但特定于 Helm 的 include 函数代替 template:
{{ include "my-chart.nodeaffinity" (include "my-chart.fullname" .) | toYaml | nindent 8 }}
{{/*^^^^^^ not template ^--- need parens here ---^ */}}
template 是内置的 Go text/template 动作。它在其块的其余部分使用管道,并且始终将其输出发送到呈现的模板输出。所以{{ template "name" "arg" | toYaml }}读作"arg" | toYaml范围到模板,并且没有办法处理它的输出。
include 是模板语法中的扩展函数。它以与template 相同的方式呈现模板,但它返回呈现的字符串,然后可以参与管道。所以 {{ include "name" "arg" | toYaml }} 使用指定的参数调用模板,然后处理返回值。
一个推论是include总是返回一个字符串.即使看起来帮助程序模板正在生成 YAML 对象,它实际上也是一个字符串。这可能意味着您不希望 toYaml 在这里,因为它可能会导致您不需要的额外转义。
您可以在 default chart scaffolding 中看到更具体的示例。一组标准标签被定义为模板
{{- define "<CHARTNAME>.labels" -}}
helm.sh/chart: {{ include "<CHARTNAME>.chart" . }}
...
{{- end }}
使用它时,它是通过include(而不是template)使用的,它的输出是(n)indented
metadata:
labels:
{{- include "<CHARTNAME>.labels" . | nindent 4 }}