
在网页开发过程中,有时会遇到一些问题,比如在使用选择器时出现了一些显示选项的问题。其中一个常见问题是循环数据未在Go模板中传递。这个问题可能会导致选择器无法正确显示选项。为了解决这个问题,我们需要对Go模板中的数据传递进行检查和调整。在本文中,php小编新一将向大家介绍如何解决这个问题,并提供一些实用的技巧和建议。让我们一起来看看吧!
问题内容
问题在于,在使用选择器选择产品类型的网页上,选择器内的选项(值)不会显示
Products
Список продуктов
| ID продукта | ID типа | Название продукта | Вес | Единица измерения | Описание | Цена самовывоза | Цена с доставкой |
|---|---|---|---|---|---|---|---|
| {{.ProductID}} | {{.ProductType.NameType}} | {{.ProductName}} | {{.Weight}} | {{.Unit}} | {{.Description}} | {{.PricePickup}} | {{.PriceDelivery}} |
尽管这部分带有表输出的代码工作得很好
{{range .Rows}}
{{.ProductID}}
{{.ProductType.NameType}}
{{.ProductName}}
{{.Weight}}
{{.Unit}}
{{.Description}}
{{.PricePickup}}
{{.PriceDelivery}}
{{end}}
我想从代表这种结构的表中获取数据本身
package product_types
type ProductTypes struct {
IDType string `json:"type_id"`
NameType string `json:"type_name"`
}
当前代码的结果现在看起来像这样
结果1
我尝试将其更改为这样
结果变得更好了,但最后还是出现了重复
result2
解决方法
我找到了问题的答案 - 我没有在 app.go 中添加 ProductTypes 表的路径
} else if req.URL.Path == "/products.html" {
log.Printf("Обслуживание HTML-файла: %s\n", productsHTMLPath)
dataRows, err := repoProduct.FindAllProduct(context.TODO()) // Используйте функцию для получения продуктов
if err != nil {
http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
return
}
dataRows1, err := repo.FindAll(context.TODO()) // Используйте функцию для получения типов продуктов
if err != nil {
http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles(productsHTMLPath)
if err != nil {
http.Error(res, fmt.Sprintf("Не удалось парсирование шаблона: %v", err), http.StatusInternalServerError)
return
}
Rows := struct {
Products []products2.Product
ProductTypes []product_types2.ProductTypes
}{
Products: dataRows,
ProductTypes: dataRows1,
}
err = tmpl.Execute(res, Rows)
if err != nil {
http.Error(res, fmt.Sprintf("Не удалось выполнить шаблон: %v", err), http.StatusInternalServerError)
}
}
最初的代码如下所示:
} else if req.URL.Path == "/products.html" {
log.Printf("Обуслуживание HTML-файла: %s\n", productsHTMLPath)
dataRows, err := repoProduct.FindAllProduct(context.TODO()) // Используйте функцию для получения продуктов
if err != nil {
http.Error(res, fmt.Sprintf("Запрос не выполнен: %v", err), http.StatusInternalServerError)
return
}
tmpl, err := template.ParseFiles(productsHTMLPath)
if err != nil {
http.Error(res, fmt.Sprintf("Не удалось парсирование шаблона: %v", err), http.StatusInternalServerError)
return
}
err = tmpl.Execute(res, struct{ Rows []products2.Product }{dataRows})
if err != nil {
http.Error(res, fmt.Sprintf("Не удалось выполнить шаблон: %v", err), http.StatusInternalServerError)
}
}
产品.html:










