动态获取变量

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

Get variables dynamically

问题

我正在使用Go模板来使用Helm管理部署。

我有一个像这样的values.yaml文件:

env: dev
config:
   dev:
       myname: Hi
   live:
       myname: Bye

现在我想根据环境(dev,live)获取值。
像这样:

{{ .Values.config. {{.Values.env}} }}

不幸的是,这种方式不起作用,因为它显示:

bad character U+007B '{'

有没有办法使用其他值来获取值?

英文:

I'm using Go templates to manage deployments with Helm.

I have the values.yaml file like this:

env: dev
config:
   dev:
       myname: Hi
   live:
       myname: Bye

Now I'd like to get the values depending on the environment (dev, live).
Like:

{{ .Values.config. {{.Values.env}} }}

Unfortunately, this way doesn't work because it says:

bad character U+007B '{'

Is there any way to get the value using others values?

答案1

得分: 7

问题出在嵌套模板上,这不是 Go 模板的工作方式。

解决方案取决于数据的内部表示。如果数据表示为嵌套的映射,可以使用全局函数 index 来解决。

{{ index .Values.config .Values.env `myname` }}

有关管道的更多信息。

有关全局模板函数的更多信息。

英文:

The problem comes from the nested template, this is not how Go templates work.

The solution depends on the internal representation of the data. If it is represented as nested maps, a solution is to use the pipeline global function index.

{{ index .Values.config .Values.env `myname` }}

More info on pipelines.

More info on global template functions.

答案2

得分: -1

以下可能有效。我没有测试过...

{{ .Values.config.(.Values.env) }}

完整的模板语法可以在text/template文档中找到。

英文:

The following may work. I didn't test it...

{{ .Values.config.(.Values.env) }}

The full template syntax is found in the text/template documentation.

huangapple
  • 本文由 发表于 2017年7月29日 06:30:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/45383273.html
匿名

发表评论

匿名网友

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

确定