'Dynamically process template map values
I have annotations object like this:
Annotations: map[string]string{
"common": "Some GPM consistency checkers have failed.",
"t_0": "Title1",
"t_1": "Title2",
"v_0": "V1",
"v_1": "V2",
I want to print it in table like:
| Title1 | Title2 |
|---|---|
| V1 | V2 |
I started something like:
{{ range .Annotations.SortedPairs }}
{{ if match "^t_" .Name }}
<p>{{ .Value }}</p>
{{ end }}
{{ end }}
but can't really figure out how it should be done. I want to do it dynamically because there can be different number of columns
Solution 1:[1]
I think you should add a helper function to your Go template.
var testTemplate *template.Template
func main() {
var err error
testTemplate, err = template.ParseFiles("hello.gohtml")
if err != nil {
panic(err)
}
http.HandleFunc("/", handler)
http.ListenAndServe(":3000", nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
data := struct {
FindValue func(ann map[string]string, needle string) string
Annotations map[string]string
}{
FindValue,
map[string]string{
"common": "Some GPM consistency checkers have failed.",
"t_0": "Title1",
"t_1": "Title2",
"v_0": "V1",
"v_1": "V2",
},
}
err := testTemplate.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func FindValue(ann map[string]string, needle string) string {
var code = strings.Replace(needle, "t_", "", 1)
for key, val := range ann {
if key == "v_"+code {
return val
}
}
return ""
}
then you can use this function in your template like this:
{{ range $key, $value := .Annotations.SortedPairs }}
{{ if match "^t_" .$key }}
<p>{{FindValue ".$key"}}</p>
{{ end }}
{{ end }}
I hope this helps to you. if there is any problem tell me because I didn't test this code.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ttrasn |
