Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading