K
K
Kobalts2020-08-30 15:52:34
go
Kobalts, 2020-08-30 15:52:34

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"`
}


I get an error:

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

1 answer(s)
E
Evgeny Mamonov, 2020-08-30
@Kobalts

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 question

Ask a Question

731 491 924 answers to any question