I have 100's of templates that I need to use in a web application.
Is there a way to parse them once and re-use them as oppose to loading them for each request?
Assume for now that the templates don't take in a model, they are simply static templates (to make it simpler).
The templates are stored in the below folder structure, so based on the theme variable I will know where to get the template from.
/views/{theme}/index.tmpl
So my hanlder so far is like this:
func RenderPage(w http.ResponseWriter, r *http.Request) {
var theme := // set template theme based on some condition
}
How can I preload all the templates, and then somehow fetch the correct one and render it to the browser in this handler?
You could do something like the following, load a map who's index is the Template name declared in the template by {{ define "Name" }}, and who's value is an array of files to parse. Then loop through that map and use those values to create a *template.Template and store that in a global map whose index is the template name and the value is the *template.Template value.
Then figure out which template you need, grab it from the map and execute it.
package main
import (
"html/template"
"log"
"net/http"
)
var templates map[string]*template.Template
func main() {
templates = make(map[string]*template.Template)
var template = make(map[string][]string)
template["Home"] = []string{"home.html"}
template["About"] = []string{"about.html"}
template["404"] = []string{"404.html"}
// Obviously you'd automate this ^
loadAllTemplates(&template, templates)
http.HandleFunc("/", renderCorrectTemplate)
http.ListenAndServe(":8080", nil)
}
func loadAllTemplates(templateMap *map[string][]string, templates map[string]*template.Template) {
for name, files := range *templateMap {
t, err := template.New(name).ParseFiles(files...)
if err != nil {
log.Printf("Error Parsing Template: %s", err.Error())
return
}
templates[name] = t
}
}
func renderCorrectTemplate(w http.ResponseWriter, r *http.Request) {
// This function would be different for you because you're not using GET, this is just an example.
r.ParseForm()
log.Println(r.URL.Query().Get("template"))
switch r.URL.Query().Get("template") {
case "Home":
//Gather Needed Data
err := templates["Home"].Execute(w, data)
//Handle err
case "About":
//Gather Needed Data
err := templates["About"].Execute(w, data)
//Handle err
default:
err := templates["404"].Execute(w, data)
//Handle err
}
}