'How to Parse html file just for one time

I'm trying to make a website to show some data on the index page.
The code snippet below shows my indexHandler function to parse my data.

func indexHandler(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("./templates/indexEx2.html")
if err != nil {
    panic(err.Error())
}
sortedData := sortData()
t.Execute(w, sortedData) }

The problem is that whenever I refresh the page, the elements on the page is duplicated.

This is index.html file.

<body>
<div class="row">
    <div class="column" style="background-color:#FFB695;">
        <h2>Column 1</h2>
        {{range .Artist}}
        <p>{{.}}</p>
        {{end}}
    </div>
    <div class="column" style="background-color:#96D1CD;">
        <h2>Column 2</h2>
        {{range .Title}}
        <p>{{.}}</p>
        {{end}}
    </div>
    <div class="column" style="background-color:#581eb0;">
        <h2>Column 3</h2>
        {{range .Photo}}
        <p>{{.}}</p>
        {{end}}
    </div>
    <div class="column" style="background-color:#11e318;">
        <h2>Column 3</h2>
        {{range .File}}
        <p>{{.}}</p>
        {{end}}
        
    </div>

</div> </body>

How can I solve this?



Solution 1:[1]

You can parse all templates in the init function and then only need to execute them in your handlers:

package main

import (
    "html/template"
    "log"
    "net/http"
)

var tmpl *template.Template

func init() {
    tmpl = template.Must(template.ParseGlobe("templates/*"))
}

func main() {
    http.HandleFunc("/", indexHandler)
    log.Fatalf("%s", http.ListenAndServe(":8080", nil))
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    sortedData := sortData()
    if err := tmpl.ExecuteTemplate(w, "index.html", sortedData); err != nil   {
        // Error handling ...
    }
}

In this way, the templates are only parsed once when the application is started.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1