Q
Q
qwex2016-06-29 19:48:50
go
qwex, 2016-06-29 19:48:50

How to get data from the database and display it in the template?

Hello, I can’t display data in the template, I don’t understand what my problem is.
Passing data to the template:

t, err := template.ParseFiles("views/admin/news/news.html")
    if err != nil {
      log.Println(err)
    }
    rslts := models.GetNews()
    t.ExecuteTemplate(w, "news", rslts)

Models.GetNews() function code
type Results struct {
  Id          int
  Title       string
  Url         string
  Description string
  Time        string
  Src         string
}

func GetNews() []*Results {
  db, err := sql.Open("mysql", "user:[email protected]/dbname")
  if err != nil {
    log.Println(err)
  }
  defer db.Close()
  rows, err := db.Query("SELECT * FROM news")
  if err != nil {
    log.Println(err)
  }
  rslts := make([]*Results, 0)
  for rows.Next() {
    rslt := new(Results)
    rows.Scan(&rslt.Id, &rslt.Title, &rslt.Url, &rslt.Description, &rslt.Time, &rslt.Src)
    rslts = append(rslts, rslt)
  }

  return rslts
}

Then I try to display in the template:
{{ range . }}
                                  <tr>
                                      <td  style="text-align: center;">{{ .rslts.Id }}</td>
                                      <td  style="text-align: center;">{{ .rslts.Description }}</td>
                                      <td  style="text-align: center;">{{ .rslts.Time }}</td>
                                      <td class="text-right" style="text-align: center;"><a href="#"><i class="pe-7s-junk"></i></a></td>
                                  </tr>
                                  {{ end }}

The problem is with the output to the template, everything is in order with the GetNews () function - the data is received.
Googled, tried a bunch of different options, nothing comes out.
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2016-06-29
@valerafedorchenko

you need not .rslts.Id, but simply .Id, you are already passing the insides of rslts, you don’t need to write its name again. Moreover, you have a cycle there and inside it you access one element of the rslts array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question