登录
首页 >  Golang >  Go问答

是否可以在 go template 的模板中使用模板

来源:stackoverflow

时间:2024-04-14 19:06:34 391浏览 收藏

本篇文章给大家分享《是否可以在 go template 的模板中使用模板》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。

问题内容

使用 https://golang.org/pkg/text/template/,我有时需要在访问路径中使用变量(对于 kubernetes 部署)。

我最终写了这样的东西:

{{ if (eq .Values.cluster "aws" }}{{ .Values.redis.aws.masterHost | quote }}{{else}}{{ .Values.redis.gcp.masterHost | quote }}{{end}}

我真正想写的是 {{ .values.redis.{{.values.cluster}}.masterhost |引用 }} ,它无法编译。

有没有办法写类似的东西? (因此在访问路径中有一种变量)。


解决方案


您可以使用 _helpers.tpl 文件来定义逻辑并使用值进行操作。

_helpers.tpl

{{/*
get redis host based on cluster.
*/}}
{{- define "chart.getredis" -}}
{{- if eq .values.cluster "aws" -}}
{{- .values.redis.aws.masterhost | quote -}}
{{- else -}}
{{- .values.redis.gcp.masterhost | quote -}}
{{- end -}}
{{- end -}}

values.yaml

cluster: local
redis:
  aws:
    masterhost: "my-aws-host"
  gcp:
    masterhost: "my-gcp-host"

并在您的部署中使用它(这里有一个 configmap 示例以使其简短)

configmap.yaml

apiversion: v1
kind: configmap
metadata:
  name: configmap
data:
  redis: {{ template "chart.getredis" . }}

输出:

helm install --dry-run --debug mychart

[debug] created tunnel using local port: '64712'

...

computed values:
cluster: local
redis:
  aws:
    masterhost: my-aws-host
  gcp:
    masterhost: my-gcp-host

hooks:
manifest:

---
# source: mychart/templates/configmap.yaml
apiversion: v1
kind: configmap
metadata:
  name: configmap
data:
  redis: "my-gcp-host"

将集群值设置为 aws:

helm install --dry-run --debug mychart --set-string=cluster=aws

[debug] Created tunnel using local port: '64712'

...

COMPUTED VALUES:
cluster: local
redis:
  aws:
    masterHost: my-aws-host
  gcp:
    masterHost: my-gcp-host

HOOKS:
MANIFEST:

---
# Source: mychart/templates/configmap.yaml
apiVersion: v1
kind: ConfigMap
metadata:
  name: Configmap
data:
  redis: "my-aws-host"

以上就是《是否可以在 go template 的模板中使用模板》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>