2

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

colm.anseo
  • 19,337
  • 4
  • 43
  • 52
user122222
  • 2,179
  • 4
  • 35
  • 78
  • Check https://pkg.go.dev/text/template#hdr-Variables, you can range over map just like in go. `{{ range $key, $value := .Annotations.SortedPairs }}`. – medasx Apr 28 '22 at 08:21

1 Answers1

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.

ttrasn
  • 4,322
  • 4
  • 26
  • 43