Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate through a list in a Go template

Tags:

go

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}}
like image 467
Leahcim Avatar asked Aug 09 '14 14:08

Leahcim


1 Answers

You have two errors here.

  1. 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.

  2. .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.

like image 64
Stephen Weinberg Avatar answered Oct 18 '22 01:10

Stephen Weinberg