Search code examples
gostructslicego-html-template

How to access an element of a struct which is inside a struct of slice in gohtml?


I have a struct A with a slice B of struct C and other datatype. I am passing it to the gohtml template. How can I access the elements of struct C in gohtml template.

type Str1 struct{
      var_x string
      var_y string
}

type Str2 struct {
      var_a []Str1
      var_b string
}
func main(){

B := make([]Str1], 0)

//code to append values of struct Str1 to Slice object B

str_var := Str2{B,"Good"} 

tpl = template.Must(template.ParseGlob("template/*.gohtml"))

tpl.ExecuteTemplate(w, "example.gohtml", str_var)

}

My question is about looping over the underlying slice and accessing the "var_x & var_y" in gohtml code. Which in the below sample example is "A, Apple, B, Ball.... "

{[{A Apple} {B Ball} {C Cat} {A Air} {B Bat} {C Coat} {D Dog} {E Ear}] Good}


Solution

  • Export the fields by starting the field name with an uppercase Unicdoe character.

    type Str1 struct {
        Var_x string
        Var_y string
    }
    
    type Str2 struct {
        Var_a []Str1
        Var_b string
    }
    

    Use the . operator to reference fields of the dot value.

     {{range .Var_a}}{{.Var_x}}: {{.Var_y}}; {{end}}
    

    https://play.golang.org/p/KTlSWy10c4R