英文:
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: "$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
}
英文:
In this code, I want to use and give a specific detail in the HTML file like heading or price.
The problem is that, there are multiple headings and prices and when I print the specific one, it prints the specific data successfully but I don't know how to use it in an HTML file to print the specific data there. All I know about GOHTML is {{.Heading}}
but it does not work. Is there any other way?
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
}
答案1
得分: 0
你可以使用内置的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
英文:
You may use the builtin index
template function to get an element from a slice:
{{ (index . 1).Heading }}
Testing it:
t := template.Must(template.New("").Parse(`{{ (index . 1).Heading }}`))
if err := t.Execute(os.Stdout, Detail); err != nil {
panic(err)
}
Which outputs (try it on the Go Playground):
Second Cloth
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论