html - 如何在golang模板中使用对象数组?

标签 html go templates

我有一个数组 products 。这是我的HomeHandler获取产品列表并将其发送到 home.html 的方法.

func (f *FrontendServer) HomeHandler(w http.ResponseWriter, h *http.Request) {
    products := ListProducts()
    parsedTemplate, _ := template.ParseFiles("templates/home.html")
    fmt.Printf("type of product %T\n", products)
    fmt.Println("PRODUCTS\n", products)
    err := parsedTemplate.Execute(w, products)
    if err != nil {
        log.Fatal("Error executing template:", err)
    }
}

这是我的home.html文件。

<html>
  <head>
    <meta charset="utf-8">
    <title>First Template</title>
    <link rel="stylesheet" href="/static/styles/home.css">
  </head>
  <body>
  <ul>
    {{range .products}}
    <li>
      {{$.name}}
    </li>
     {{end}}
  </ul>
  </body>
</html>

我尝试过很多技术,例如 $.Products , .Products等等。当我向主页发出请求时,总是出现错误,如下所示:

2021/05/17 00:19:26 Error executing template:template: home.html:9:12: executing "home.html" at <.products>: can't evaluate field products in type []main.Product

当我打印产品时,其类型如下。

[{1001 Product 1 A product 12.99} {1002 Product 2 A product 13.99} {1003 Product 3 A product 14.99} {1004 Product 4 A product 15.99} {1005 Product 5 A product 16.99} {1006 Product 6 A product 18.99} {1007 Product 7 A product 19.99} {1008 Product 8 A product 20.99} {1009 Product 9 A product 21.99} {1010 Product 1 A product 22.99}]

这是我的产品结构:

type Product struct {
    ID          int     `json:"product_id"`
    Name        string  `json:"product_name"`
    Description string  `json:"product_description"`
    Price       float32 `json:"product_price"`
}

我想列出 <li> 中的所有产品标签。我如何迭代此场景中的所有项目?

最佳答案

表达式

{{range .products}}

. 中查找名为 products 的变量,其中 . 是当前上下文,在顶层,它是参数到执行。根据错误,您已经传递了一个产品数组。因此,请执行以下操作之一:

或者:

{{range .}}

这意味着,范围是传递给 Executeproducts 数组,或者

    err := parsedTemplate.Execute(w, map[string]interface{}{"products":products})

这将创建一个包含 products 的映射,它是一个数组,因此 {{range .products}} 可以工作。

关于html - 如何在golang模板中使用对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67561714/

相关文章:

javascript - 使用自定义 header 获取请求失败

javascript - 单击事件时使用 jQuery 在 Smarty 输入字段中动态主机名

html - 打印可滚动 div 的内容

jquery - 动态设置特定单元格的颜色

go - 如何解耦这种传递依赖

c++ - 递归模板解释C++

C++ "was not declared in this scope"在派生类中覆盖纯虚方法时

html - 移动屏幕上的固定页面大小

javascript - Bootstrap 3 - 静态表头实现

使用 http.server 转到上下文