登录
首页 >  Golang >  Go问答

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>
    &lt;input type=&quot;text&quot; id=&quot;productName&quot; name=&quot;productName&quot; required&gt;

    <label for="weight">Weight:</label>
    &lt;input type=&quot;number&quot; id=&quot;weight&quot; name=&quot;weight&quot; required&gt;

    <label for="typeSelect">Product Type:</label>
    &lt;select class=&quot;form-control&quot; id=&quot;typeSelect&quot; name=&quot;TypeID&quot;&gt;
        {{ range .Rows}}
        <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option>
        {{ end }}
    &lt;/select&gt;

    <label for="unit">Unit:</label>
    &lt;input type=&quot;text&quot; id=&quot;unit&quot; name=&quot;unit&quot; required&gt;

    <label for="description">Description:</label>
    &lt;input type=&quot;text&quot; id=&quot;description&quot; name=&quot;description&quot; required&gt;

    <label for="pricePickup">Price Pickup:</label>
    &lt;input type=&quot;number&quot; id=&quot;pricePickup&quot; name=&quot;pricePickup&quot; required&gt;

    <label for="priceDelivery">Price Delivery:</label>
    &lt;input type=&quot;number&quot; id=&quot;priceDelivery&quot; name=&quot;priceDelivery&quot; required&gt;


    <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>
&lt;select class=&quot;form-control&quot; id=&quot;typeSelect&quot; name=&quot;TypeID&quot;&gt;
    {{ range .Rows}}
    <option value="{{.ProductType.IDType}}">{{ .ProductType.NameType }}</option>
    {{ end }}
&lt;/select&gt;

结果变得更好了,但最后还是出现了重复

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>
    &lt;select class=&quot;form-control&quot; id=&quot;typeSelect&quot; name=&quot;TypeID&quot;&gt;
        {{ range .ProductTypes}}
        <option value="{{.IDType}}">{{ .NameType }}</option>
        {{ end }}
&lt;/select&gt;

理论要掌握,实操不能落!以上关于《Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>