I have a function that retrieves a bunch of Tweets (of type Tweet) from a database and passes them to a template. In the template, I have to loop through the array and print the message
field for each tweet retrieved from the db. The template below doesn't display anything at all.
How do I indicate that I'm looping through an array of type Tweet and then print the message for each?
func Root(w http.ResponseWriter, r *http.Request) {
tweets := []*Tweet{}
t := template.Must(template.New("main").ParseFiles("main.html"))
err := Orm.Find(&tweets)
if err != nil {
fmt.Println("err", err)
return
}
t.ExecuteTemplate(w, "main.html", tweets)
}
main.html
{{range .Tweet}}
status: {{.message}}
{{end}}
You have two errors here.
Where does .Tweet
come from? You gave the template engine tweets, a []*Tweet as the input so .
is a slice and has no Tweet
field or key.
.message
is not exported, only exported fields may be used in a template.
The end result:
{{range .}}
status: {{.Message}}
{{end}}
Remember to modify your Tweet type to use the new field name.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With