Reputation: 33
I'm passing an array of structs to my template, the data is there but I can't find a way to access specific data, I tried many things already, here it is
My Struct
type Data struct {
Destination string
IData interface{}
}
then in my controller I have
users := []models.User {}
userRow := models.User{Name: "jon", Email: "[email protected]"}
users = append(users, userRow)
users2 := users
data := models.Data{
Destination: "content",
IData: users,
}
data2 := models.Data{
Destination: "content",
IData: users2,
}
dataFinal := []models.Data{}
dataFinal = append(dataFinal, data)
dataFinal = append(dataFinal, data2)
and this is my template, though this didn't seem to work, it does show the raw data but can't seem to access the name specifically.
{{define "content"}}
<h2>THIS IS THE BODY CONTENT</h2>
<ul>
{{.}}
{{range .}}
<li>{{.}}</li>
{{end}}
</ul>
{{end}}
edit: project: https://github.com/og2/go-og2-mvc
you may wanna run:
go get github.com/go-sql-driver/mysql
go get github.com/julienschmidt/httprouter
for it to work and should be just fine!
Upvotes: 2
Views: 875
Reputation: 417462
If the pipeline value that you pass to the "content"
template execution is dataFinal
, then you have to use two {{range}}
actions as dataFinal
itself is a slice (of type []models.Data
), and Data.IData
is also a slice (of type []model.User
).
Inside the inner {{range}}
you may refer to the User.Name
like .Name
:
<li>{{.Name}}</li>
See this working example:
const templ = `{{define "content"}}
<h2>THIS IS THE BODY CONTENT</h2>
<ul>
{{.}}
{{range .}}
<ul>
{{range .IData}}
<li>{{.Name}}</li>
{{end}}
</ul>
{{end}}
</ul>
{{end}}`
// Parsing and executing the template:
t := template.Must(template.New("").Parse(templ))
fmt.Println(t.ExecuteTemplate(os.Stdout, "content", dataFinal))
Output (try it on the Go Playground):
<h2>THIS IS THE BODY CONTENT</h2>
<ul>
[{content [{jon [email protected]}]} {content [{jon [email protected]}]}]
<ul>
<li>jon</li>
</ul>
<ul>
<li>jon</li>
</ul>
</ul>
<nil>
Upvotes: 2