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

Go Template dynamically obtains variables

PHPz
Release: 2024-02-05 23:36:04
forward
1320 people have browsed it

Go Template 动态获取变量

Question content

My yml parameters look like

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

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 }}
Copy after login


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 }}
Copy after login

For indexing, use the built-in index function:

instance-min: {{ index $.parameters $key }}
Copy after login

(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) }}
Copy after login

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 }}`
Copy after login

This will output (try it on go playground):

instance-min: 1
instance-max: 2
instance-min: 4
instance-max: 6
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template