In this code, I am trying to loop over all the product details in an HTML file using range
but it is giving me an error
Error
executing "body" at <.>: range can't iterate over {[product-names...] [product-images...] [product-links...] [product-prices...]}
controllers.go
type ProductStruct struct {
Names []string
Images []string
Links []string
Prices []string
}
func ProductsList(w http.ResponseWriter, r *http.Request) error {
var pList ProductStruct
for i := 0; i < len(products.AccessColumns(0)); i {
pList.Names = append(pList.Names, products.AccessColumns(0)[i])
pList.Images = append(pList.Images, products.AccessColumns(1)[i])
pList.Links = append(pList.Links, products.AccessColumns(2)[i])
pList.Prices = append(pList.Prices, products.AccessColumns(3)[i])
}
return ProductsListTmpl.Execute(w, pList)
}
product-list.html
{{range $i := .}}
<tr>
<td data-title="No"><img src="../../static/images/{{ (index .Images $i) }}.jpg" alt="#"></td>
<td data-title="Description">
<p ><a href="{{ (index .Links $i) }}">{{ (index .Names $i) }}</a></p>
<p >Maboriosam in a tonto nesciung eget distingy magndapibus.</p>
</td>
<td data-title="Price"><span>${{ (index .Prices $i) }}.00 </span></td>
</tr>
{{end}}
CodePudding user response:
Error accrues because you trying to iterate {{range $i := .}}
over not related Names []string, Images []string, Links []string, Prices []string
. They can have even not equal len.
Try to refactor your solution, to have something like this(It's just a draft):
controllers.go
type ProductStruct struct {
Names string
Images string
Links string
Prices string
}
func ProductsList(w http.ResponseWriter, r *http.Request) error {
var pList []ProductStruct
for i := 0; i < len(products.AccessColumns(0)); i {
pList = append(pList, ProductStruct{products.AccessColumns(0)[i],
products.AccessColumns(1)[i],
products.AccessColumns(2)[i],
products.AccessColumns(3)[i],
})
}
return ProductsListTmpl.Execute(w, pList)
}
product-list.html
{{range .}}
<tr>
<td data-title="No"><img src="../../static/images/{{ (.Images}}.jpg" alt="#"></td>
<td data-title="Description">
<p ><a href=".Links}}">{{.Names}}</a></p>
<p >Maboriosam in a tonto nesciung eget distingy magndapibus.</p>
</td>
<td data-title="Price"><span>${{ .Prices}}.00 </span></td>
</tr>
{{end}}