Search code examples
htmlgotemplatesgo-templates

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
}

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