A
A
Abcdefgk2018-06-26 14:40:02
go
Abcdefgk, 2018-06-26 14:40:02

Loop in Go template, where is the data?

I pass here the beginning of the relationship between the http-server and the database. But suddenly I stumbled not on the database - everything is clear here.
Here I have two structures-blanks

type Book struct {
  isbn   string
  title  string
  author string
  price  float32
}

var Books struct {
  Items []*Book
}

and the corresponding table in the database (PostgresQL, but it doesn't matter) with three lines
. I make a query and get the result:
for rows.Next() {
  bk := new(Book)
  err := rows.Scan(&bk.isbn, &bk.title, &bk.author, &bk.price)
  if err != nil {
    http.Error(w, http.StatusText(500), 500)
    return
  }
  Books.Items = append(Books.Items, bk)
}

Now if I give the result as a server response like this in a loop
for _, b := range Books.Items {
  fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", b.isbn, b.title, b.author, b.price)
}

then everything is fine.
But I want, for example, to display these lines in the template, and also add a simple form there and try to add from it to the database. But first - display what is on the page. It would seem that we only need to transfer the cycle to the template.
I write the following line in the file
var str = `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Books</title>
</head>
<body>
  {{ range .Items }}<div><b>{{ .isbn }}</b> {{ .title }} {{ .author }} {{ .price }}</div>
  {{else}}<div><strong>no rows</strong></div>
  {{end}}
</body>
</html>
`

And I replace the loop in the code with this
html, err := template.New("books").Parse(str)
if err != nil {
  fmt.Println(err)
}
html.Execute(w, Books)

and nothing works.
Please explain what is wrong?
It does not give any errors, and the data is not inserted into the template. The source code of the page is as follows
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Books</title>
</head>
<body>
  <div><b>

and on this execution (Execute) just stops.
Now, I don't know what to look for.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
U
uvelichitel, 2018-06-26
@Abcdefgk

To get started, just try to export the fields of the structure, that is, name them with a capital letter

type Book struct {
  Isbn   string
  Title  string
  Author string
  Price  float32
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question