如何使用Golang打印HTML文件中的特定内容?

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2021年11月12日 15:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/69939227.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定