Answer the question
In order to leave comments, you need to log in
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)
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
}
{{ 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 }}
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question