Home  >  Article  >  Backend Development  >  Go Template dynamically obtains variables

Go Template dynamically obtains variables

PHPz
PHPzforward
2024-02-05 23:36:041233browse

Go Template 动态获取变量

Question content

My yml parameters look like

nodes: one, two
instanceminone: 1
instancemaxone: 2
instancemintwo: 4
instancemaxtwo: 6

Is there a way to dynamically read e.g. instanceminone using go templates, where the variable name consists of instancemin the dynamic value from the node list?

Something like this (this obviously doesn't work but just gives an idea of ​​what I want to achieve)

{{ - range $nodeName := (split .Parameters.nodes) } } } }
   instance-min: {{ .Parameters.instanceMin$nodeName }}
   instance-max: {{ .Parameters.instanceMan$nodeName }}
{{ - end }}

Correct answer


To achieve what you want, you must solve 2 tasks:

  • String concatenation
  • Indexing using dynamic values

For connections you can use the built-in print function like

{{ $key := print "instancemin" $nodename }}

For indexing, use the built-in index function:

instance-min: {{ index $.parameters $key }}

(Note: The {{range}} operation changes points, so you need $ within it to reference the loop variable outside.)

or one line:

instance-min: {{ index $.parameters (print "instancemin" $nodename) }}

View runnable demo:

func main() {
    t := template.must(template.new("").parse(src))

    params := map[string]any{
        "parameters": map[string]any{
            "nodes":          []string{"one", "two"},
            "instanceminone": 1,
            "instancemaxone": 2,
            "instancemintwo": 4,
            "instancemaxtwo": 6,
        },
    }

    if err := t.execute(os.stdout, params); err != nil {
        panic(err)
    }
}

const src = `{{- range $idx, $nodename := .parameters.nodes }}
   instance-min: {{ index $.parameters (print "instancemin" $nodename) }}
   instance-max: {{ index $.parameters (print "instancemax" $nodename) }}
{{- end }}`

This will output (try it on go playground):

instance-min: 1
instance-max: 2
instance-min: 4
instance-max: 6

The above is the detailed content of Go Template dynamically obtains variables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete