【问题标题】:How to loop over all the product details in an html file?如何遍历 html 文件中的所有产品详细信息?
【发布时间】:2022-01-22 07:56:20
【问题描述】:

在这段代码中,我尝试使用 range 循环遍历 HTML 文件中的所有产品详细信息,但它给了我一个错误

错误

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 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}}

【问题讨论】:

  • 有人回答我的问题吗?
  • 有人回答吗??

标签: loops go range


【解决方案1】:

由于您尝试在不相关的Names []string, Images []string, Links []string, Prices []string 上迭代{{range $i := .}},因此产生了错误。他们甚至可以有不相等的 len。

尝试重构你的解决方案,得到这样的东西(这只是一个草稿):

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 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}}

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 2012-05-28
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多