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!
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!
List[i].ID | List[i].Name | List[i].Test |
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)
}
}
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)