在這段代碼中,我試圖回圈使用 HTML 檔案中的所有產品詳細資訊,range但它給了我一個錯誤
錯誤
executing "body" at <.>: range can't iterate over {[product-names...] [product-images...] [product-links...] [product-prices...]}
控制器.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)
}
產品串列.html
{{range $i := .}}
<tr>
<td class="image" data-title="No"><img src="../../static/images/{{ (index .Images $i) }}.jpg" alt="#"></td>
<td class="product-des" data-title="Description">
<p class="product-name"><a href="{{ (index .Links $i) }}">{{ (index .Names $i) }}</a></p>
<p class="product-des">Maboriosam in a tonto nesciung eget distingy magndapibus.</p>
</td>
<td class="price" data-title="Price"><span>${{ (index .Prices $i) }}.00 </span></td>
</tr>
{{end}}
uj5u.com熱心網友回復:
錯誤是因為您嘗試迭代{{range $i := .}}不相關Names []string, Images []string, Links []string, Prices []string的。他們甚至可以有不相等的 len。
嘗試重構你的解決方案,得到這樣的東西(這只是一個草稿):
控制器.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)
}
產品串列.html
{{range .}}
<tr>
<td class="image" data-title="No"><img src="../../static/images/{{ (.Images}}.jpg" alt="#"></td>
<td class="product-des" data-title="Description">
<p class="product-name"><a href=".Links}}">{{.Names}}</a></p>
<p class="product-des">Maboriosam in a tonto nesciung eget distingy magndapibus.</p>
</td>
<td class="price" data-title="Price"><span>${{ .Prices}}.00 </span></td>
</tr>
{{end}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/419704.html
標籤:
上一篇:為什么我的go處理程式沒有生成有效的FormData?
下一篇:去統計動態url呼叫
