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

2 html templates go

我有一个数组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)
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的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>
Run Code Online (Sandbox Code Playgroud)

我尝试了很多技术,例如$.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
Run Code Online (Sandbox Code Playgroud)

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

[{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}]
Run Code Online (Sandbox Code Playgroud)

这是我的产品结构:

type Product struct {
    ID          int     `json:"product_id"`
    Name        string  `json:"product_name"`
    Description string  `json:"product_description"`
    Price       float32 `json:"product_price"`
}
Run Code Online (Sandbox Code Playgroud)

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

Bur*_*dar 5

表达方式

{{range .products}}
Run Code Online (Sandbox Code Playgroud)

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

任何一个:

{{range .}}
Run Code Online (Sandbox Code Playgroud)

products这意味着,传递给 的数组范围Execute,或

    err := parsedTemplate.Execute(w, map[string]interface{}{"products":products})
Run Code Online (Sandbox Code Playgroud)

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

  • 另外,只是为了添加到您的答案 Burak,在范围内它应该是 `{{.Name}}` 而不是 baris 尝试的 `{{$.name}}` 。大小写很重要,“$.”是根上下文,而不是迭代变量。 (3认同)