在网页开发过程中,有时会遇到一些问题,比如在使用选择器时出现了一些显示选项的问题。其中一个常见问题是循环数据未在Go模板中传递。这个问题可能会导致选择器无法正确显示选项。为了解决这个问题,我们需要对Go模板中的数据传递进行检查和调整。在本文中,php小编新一将向大家介绍如何解决这个问题,并提供一些实用的技巧和建议。让我们一起来看看吧!
问题内容
问题在于,在使用选择器选择产品类型的网页上,选择器内的选项(值)不会显示
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Products</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1 id="Список-продуктов">Список продуктов</h1> <form id="addProductForm"> <label for="productName">Product Name:</label> <input type="text" id="productName" name="productName" required> <label for="weight">Weight:</label> <input type="number" id="weight" name="weight" required> <label for="typeSelect">Product Type:</label> <select class="form-control" id="typeSelect" name="TypeID"> {{ range .Rows}} <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option> {{ end }} </select> <label for="unit">Unit:</label> <input type="text" id="unit" name="unit" required> <label for="description">Description:</label> <input type="text" id="description" name="description" required> <label for="pricePickup">Price Pickup:</label> <input type="number" id="pricePickup" name="pricePickup" required> <label for="priceDelivery">Price Delivery:</label> <input type="number" id="priceDelivery" name="priceDelivery" required> <button type="button" onclick="addProduct()">Add Product</button> </form> <table id="productTable"> <tr> <th>ID продукта</th> <th>ID типа</th> <th>Название продукта</th> <th>Вес</th> <th>Единица измерения</th> <th>Описание</th> <th>Цена самовывоза</th> <th>Цена с доставкой</th> </tr> {{range .Rows}} <tr> <td>{{.ProductID}}</td> <td>{{.ProductType.NameType}}</td> <td>{{.ProductName}}</td> <td>{{.Weight}}</td> <td>{{.Unit}}</td> <td>{{.Description}}</td> <td>{{.PricePickup}}</td> <td>{{.PriceDelivery}}</td> </tr> {{end}} </table> <script> function addProduct() { // Получение данных из формы var form = document.getElementById("addProductForm"); var formData = new FormData(form); // Отправка данных на сервер fetch("/add_product", { method: "POST", body: formData, }) .then(response => response.json()) .then(data => { // Обработка ответа от сервера console.log("Product created:", data); // Очистка формы или выполнение других действий при необходимости form.reset(); }) .catch(error => console.error("Error:", error)); } </script> </body> </html>
尽管这部分带有表输出的代码工作得很好
{{range .Rows}} <tr> <td>{{.ProductID}}</td> <td>{{.ProductType.NameType}}</td> <td>{{.ProductName}}</td> <td>{{.Weight}}</td> <td>{{.Unit}}</td> <td>{{.Description}}</td> <td>{{.PricePickup}}</td> <td>{{.PriceDelivery}}</td> </tr> {{end}}
我想从代表这种结构的表中获取数据本身
package product_types type ProductTypes struct { IDType string `json:"type_id"` NameType string `json:"type_name"` }
当前代码的结果现在看起来像这样
结果1
我尝试将其更改为这样
<label for="typeSelect">Product Type:</label> <select class="form-control" id="typeSelect" name="TypeID"> {{ range .Rows}} <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option> {{ end }} </select>
结果变得更好了,但最后还是出现了重复
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:
<label for="typeSelect">Product Type:</label> <select class="form-control" id="typeSelect" name="TypeID"> {{ range .ProductTypes}} <option value="{{.IDType}}">{{ .NameType }}</option> {{ end }} </select>
以上是在网页上的选择器中显示选项时出现问题:循环 {{ range }} 的数据未在 Go 模板中传递的详细内容。更多信息请关注PHP中文网其他相关文章!

本文解释了GO的软件包导入机制:命名imports(例如导入“ fmt”)和空白导入(例如导入_ fmt; fmt;)。 命名导入使包装内容可访问,而空白导入仅执行t

本文解释了Beego的NewFlash()函数,用于Web应用程序中的页间数据传输。 它专注于使用newflash()在控制器之间显示临时消息(成功,错误,警告),并利用会话机制。 Lima

本文详细介绍了MySQL查询结果的有效转换为GO结构切片。 它强调使用数据库/SQL的扫描方法来最佳性能,避免手动解析。 使用DB标签和Robus的结构现场映射的最佳实践

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

本文详细介绍了在GO中详细介绍有效的文件,将OS.WriteFile(适用于小文件)与OS.openfile和缓冲写入(最佳大型文件)进行比较。 它强调了使用延迟并检查特定错误的可靠错误处理。

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版
视觉化网页开发工具

记事本++7.3.1
好用且免费的代码编辑器

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器