I have a struct example with a two dimensinal array:
type Foo struct{
testArray[9][9] int
}
I would like to access it by a template.
For example: tmpl.Execute(w, foo)
//foo is a pointer to Foo struct and w is the parsed html site
How can I access the array in the template? For a one dimensional array with the old template package there is the code:
{.repeated section testArray}
<p>{@}</p>
{.end}
but what is the syntax for a two dimension array? For example I must access testArray[0][0]
I have solved your problem accidentally with the new template package. But maybe the old one works similar. Have you tried something like:
{.repeated section testArray}<p>{.repeated section @}{@} {.end}</p>{.end}
(untested)
Anyway, here is my solution with the new template package. Maybe you can use it somehow :D
package main
import (
"os"
"text/template"
)
type Foo struct {
Data [9][9]int
}
func main() {
tmpl := template.Must(template.New("example").Parse(`
<table>
{{range .Data}}
<tr>
{{range .}}<td>{{.}}</td>{{end}}
</tr>
{{end}}
`))
foo := new(Foo)
foo.Data[2][1] = 4
tmpl.Execute(os.Stdout, foo)
}
this little sample should help you.
package main
import (
"net/http"
"text/template"
)
type Foo struct {
Array [9][9]int
}
func handler(w http.ResponseWriter, r *http.Request) {
var foo Foo
for i := 0; i < len(foo.Array); i++ {
for j := 0; j < len(foo.Array); j++ {
foo.Array[i][j] = j
}
}
tmpl := template.Must(template.New("example").Parse(`
<html>
<body>
<table>
{{ $a := .Array }}
{{ range $a }}
<tr>
{{ $elem := . }}
{{ range $elem }}
{{ printf "<td>%d<td>" . }}
{{ end}}
</tr>
{{end}}
</table>
</body>
</html>
`))
tmpl.Execute(w, foo)
}
func main() {
bindAddress := "127.0.0.1:8080"
http.HandleFunc("/", handler)
http.ListenAndServe(bindAddress, nil)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.