在此代碼中,我想在 HTML 檔案中使用并提供特定的詳細資訊,例如標題或價格。
問題是,有多個標題和價格,當我列印特定的標題和價格時,它會成功列印特定資料,但我不知道如何在 HTML 檔案中使用它在那里列印特定資料。我所知道的關于 GOHTML 是{{.Heading}}但它不起作用。有沒有其他辦法?
package main
import "net/http"
type Details struct {
Heading string
Price string
}
var Detail = []Details{
{
Heading: "First Cloth",
Price: "$59",
},
{
Heading: "Second Cloth",
Price: "$49",
},
}
func Main(w http.ResponseWriter, r *http.Request) {
HomeTmpl.Execute(w, Detail)
// fmt.Println(Detail[1].Heading) // For specific data
}
uj5u.com熱心網友回復:
您可以使用內置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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358746.html
