Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of struct in templates

Tags:

go

beego

Please, help me. I have type with struct

type myType struct {
    ID string 
    Name
    Test 
}

And have array of type

var List []MyType;

How to i can print in template my List with all struct fields?

Thank you!

like image 585
Максим Ткаченко Avatar asked Oct 27 '25 05:10

Максим Ткаченко


1 Answers

Use range and variable assignments. See the appropriate sections of the text/template documentation. Also see example below:

package main

import (
    "fmt"
    "os"
    "text/template"
)

type myType struct {
    ID   string
    Name string
    Test string
}

func main() {
    list := []myType{{"id1", "name1", "test1"}, {"i2", "n2", "t2"}}

    tmpl := `
<table>{{range $y, $x := . }}
  <tr>
    <td>{{ $x.ID }}</td>
    <td>{{ $x.Name }}</td>
    <td>{{ $x.Test }}</td>
  </tr>{{end}}
</table>
`

    t := template.Must(template.New("tmpl").Parse(tmpl))

    err := t.Execute(os.Stdout, list)
    if err != nil {
        fmt.Println("executing template:", err)
    }
}

https://play.golang.org/p/W5lRPxD6r-

like image 173
Amit Kumar Gupta Avatar answered Oct 30 '25 07:10

Amit Kumar Gupta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!