Is there a way to display a field of a map[key-string] with value-struct, in html, in golang?

649 Views Asked by At

I have a datatype of map[key-string] value-struct, and I'm trying to display a field(Timing) of the struct

I tried all sort of variations for an hour, can't seem to figure it out. Would appreciate any guidance on this, thank you!

Also apologies on the formatting, am new, do bear with me! my code

1

There are 1 best solutions below

2
On BEST ANSWER

Instead of inner loop, use {{$value.Timing}}.

// You can edit this code!
// Click here and start typing.
package main

import (
    "os"
    "text/template"
)

type A struct {
    Timing string
}

func main() {
    inp := `
    <html>
    
    {{ range $key,$value:= .}}
        Key:{{$key}}, Timing {{$value.Timing}}
    {{end}}
    </html>
`
    valueMap := map[string]A{
        "key": A{
            Timing: "1",
        },
    }
    t, err := template.New("test").Parse(inp)
    if err != nil {
        panic(err)
    }
    err = t.Execute(os.Stdout, valueMap)
    if err != nil {
        panic(err)
    }
}