登录
首页 >  Golang >  Go问答

Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示

来源:stackoverflow

时间:2024-02-04 10:11:14 413浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Go模板中传递的数据在网页选择器中循环时出现问题:{{ range }}的循环数据未正确显示》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

问题在于,在使用选择器选择产品类型的网页上,选择器内的选项(值)不会显示




    
    
    Products
    


Список продуктов

{{range .Rows}} {{end}}
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:


    

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

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