Answer the question
In order to leave comments, you need to log in
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
}
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)
}
for _, b := range Books.Items {
fmt.Fprintf(w, "%s, %s, %s, £%.2f\n", b.isbn, b.title, b.author, b.price)
}
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>
`
html, err := template.New("books").Parse(str)
if err != nil {
fmt.Println(err)
}
html.Execute(w, Books)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Books</title>
</head>
<body>
<div><b>
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question