在网页上的选择器中显示选项时出现问题:循环 {{ range }} 的数据未在 Go 模板中传递
在网页开发过程中,有时会遇到一些问题,比如在使用选择器时出现了一些显示选项的问题。其中一个常见问题是循环数据未在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>Список продуктов</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中文网其他相关文章!

热AI工具

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

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

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

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

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Golang在性能和可扩展性方面优于Python。1)Golang的编译型特性和高效并发模型使其在高并发场景下表现出色。2)Python作为解释型语言,执行速度较慢,但通过工具如Cython可优化性能。

Golang在并发性上优于C ,而C 在原始速度上优于Golang。1)Golang通过goroutine和channel实现高效并发,适合处理大量并发任务。2)C 通过编译器优化和标准库,提供接近硬件的高性能,适合需要极致优化的应用。

goisidealforbeginnersandsubableforforcloudnetworkservicesduetoitssimplicity,效率和concurrencyFeatures.1)installgromtheofficialwebsitealwebsiteandverifywith'.2)

Golang适合快速开发和并发场景,C 适用于需要极致性能和低级控制的场景。1)Golang通过垃圾回收和并发机制提升性能,适合高并发Web服务开发。2)C 通过手动内存管理和编译器优化达到极致性能,适用于嵌入式系统开发。

GoimpactsdevelopmentPositationalityThroughSpeed,效率和模拟性。1)速度:gocompilesquicklyandrunseff,ifealforlargeprojects.2)效率:效率:ITScomprehenSevestAndArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdArdEcceSteral Depentencies,增强开发的简单性:3)SimpleflovelmentIcties:3)简单性。

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

Golang和C 在性能竞赛中的表现各有优势:1)Golang适合高并发和快速开发,2)C 提供更高性能和细粒度控制。选择应基于项目需求和团队技术栈。
