4

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!

2 Answers2

3

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-

Amit Kumar Gupta
  • 17,184
  • 7
  • 46
  • 64
  • 1
    Do use [`html/template`](https://golang.org/pkg/html/template/) whenever the output is HTML (it is here), because it is safe against code injection. – icza Jul 02 '16 at 10:37
0

If you're talking about HTML template, here's what it'd look like:

{{range $idx, $item := .List}}
<div>
    {{$item.ID}}
    {{$item.Name}}
    {{$item.Test}}
</div>
{{end}}

And this is how you'd pass that slice to the template.

import (
htpl "html/template"
"io/ioutil"
)

content, err := ioutil.ReadFile("full/path/to/template.html")
if err != nil {
    log.Fatal("Could not read file")
    return
}

tmpl, err := htpl.New("Error-Template").Parse(string(content))
if err != nil {
    log.Fatal("Could not parse template")
}


var html bytes.Buffer
List := []MyType // Is the variable holding the actual slice with all the data
tmpl.Execute(&html, type struct {
    List []MyType
}{
    List
})
fmt.Println(html)
KBN
  • 2,915
  • 16
  • 27