Answer the question
In order to leave comments, you need to log in
How to go structure from base to html template in gin?
I am trying to output from database to html:
{{ define "users/index.tmpl" }}
<html><h1>
{{ range .values }} {{ .name }} {{ end }}
</h1>
</html>
{{ end }}
rows, err := conn.Queryx("SELECT id, name FROM users")
for rows.Next() {
if rows.StructScan(&user) != nil {
log.Fatalln(err)
}
}
defer rows.Close()
ctx.HTML(http.StatusOK, "users/index.tmpl", gin.H{"values": user})
type User struct {
ID int `db:"id"`
Name string `db:"name"`
}
template: index.tmpl:4:28: executing "users/index.tmpl" at <.values>: range can't iterate over
Answer the question
In order to leave comments, you need to log in
You need to iterate the slice, not the structure, i.e. []Users.
Here is a working example.
rows, err := conn.Queryx("SELECT id, name FROM users")
if err != nil {
log.Fatalln(err)
}
defer rows.Close()
users := []User{}
for rows.Next() {
if rows.StructScan(&user) != nil {
log.Fatalln(err)
}
users = append(users, user)
}
ctx.HTML(http.StatusOK, "users/index.tmpl", gin.H{"values": users})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question