Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示
来源:stackoverflow
时间:2024-02-04 10:11:14 413浏览 收藏
在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!
问题内容问题在于,在使用选择器选择产品类型的网页上,选择器内的选项(值)不会显示
<!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>理论要掌握,实操不能落!以上关于《Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习