如何使用 golang 在 HTML 文件中打印特定内容?

How to print the specific in an HTML file using golang?

在此代码中,我想在 HTML 文件中使用并提供特定的详细信息,例如标题或价格。

问题是,有多个标题和价格,当我打印特定的一个时,它成功打印了特定的数据,但我不知道如何在 HTML 文件中使用它来打印具体数据在那里。我对 GOHTML 的了解是 {{.Heading}} 但它不起作用。还有其他办法吗?

package main

import "net/http"

type Details struct {
    Heading string
    Price   string
}

var Detail = []Details{
    {
        Heading: "First Cloth",
        Price:   "",
    },
    {
        Heading: "Second Cloth",
        Price:   "",
    },
}

func Main(w http.ResponseWriter, r *http.Request) {
    HomeTmpl.Execute(w, Detail)
    // fmt.Println(Detail[1].Heading) // For specific data
}

您可以使用内置的 index 模板函数从切片中获取元素:

{{ (index . 1).Heading }}

正在测试:

t := template.Must(template.New("").Parse(`{{ (index . 1).Heading }}`))
if err := t.Execute(os.Stdout, Detail); err != nil {
    panic(err)
}

哪些输出(在 Go Playground 上尝试):

Second Cloth