Answer the question
In order to leave comments, you need to log in
Why is the data on the page duplicated, duplicated and duplicated, etc.?
Please someone explain this amazing effect to me.
Here is my code that takes a simple table with four fields from the database with the usual SELECT * FROM books query,
sends it to the prepared structure, reads the file with the template, parses it and sends it back to the client with the data, like this (a fragment, of course):
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)
}
if err = rows.Err(); err != nil {
http.Error(w, http.StatusText(500), 500)
return
}
f, err := ioutil.ReadFile("file.tpl")
if err != nil {
fmt.Println(err)
}
html, err := template.New("books").Parse(string(f))
if err != nil {
fmt.Println(err)
}
w.Header().Set("Cache-Control", "no-cache")
html.Execute(w, Books)
<body>
{{ range .Items }}
<div><b>{{ .Isbn }}</b> {{ .Title }} {{ .Author }} {{ .Price }}</div>
{{else}}
<div><strong>no rows</strong></div>
{{end}}
<br>
Answer the question
In order to leave comments, you need to log in
it looks like Books is declared globally and is not cleared after the request, on each request you push data into it Books.Items = append(Books.Items, bk) hence the result
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question