Introduction to Cache Templates
In previous program codes that we have studied practically, they were not efficient. Why did it happen? because every time it is accessed it will call a function and describe the data sent into the template so the process requires high levels of execution. Every time the handler is called we will always re-parse the template. So ideally the template only performs parsing once at the beginning when the application is running, then only the template data is cached (stored in memory) so there is no need to access the data and do the parsing again so that the website we create can be faster.
Implementation
Let’s try directly how this template cache mechanism works to make the website that we have created easier and faster.
Create the program code below with the handler function too
// go:embed templates/*.html
var templates embed.FS
var myTemplates = template.Must(template.ParseFS(templates, "templates/*.html"))
func TemplateCachingHandler(w http.ResponseWriter, r *http.Request) {
myTemplates.ExecuteTemplate(w, "simple.html", "Hello HTML Template")
}
then we add it to the router as below.
mux.HandleFunc("/template-cache", TemplateCachingHandler)
So when we run it, it will produce the same value, but in terms of efficiency, this access is faster than the previous post that we made.