Do I need to put patterns on a card for reuse in Go?

To handle each request in a web application, the regular template code looks like this:

t:= template.New("welcome") t, _ = t.ParseFiles("welcome.tpl") t.Execute(w, data) 

I think ParseFiles cost a lot every time. Can I reuse a template? Therefore, I improved it as follows:

 //templateMap := make(map[string][template]) //... tplName :="welcome" t := templateMap[tplName] if t=nil{ t:= template.New(tplName ) t, _ = t.ParseFiles("welcome.tpl") templateMap[tplName] = t } t.Execute(w, data) 

I wonder if it’s possible or advisable to increase efficiency by putting templates in a card or cache? I also wonder if the Execute function is thread safe or not?

func (t *Template) Execute(wr io.Writer, data interface{}) (err error)

+7
source share
2 answers

A template can actually act as a template map on its own. That's what I'm doing:

Declare a global template variable:

 var t = template.New("master") 

I actually do not use the master template, except as a container for other templates.

Then I load all the templates when the application starts:

 func init() { _, err := t.ParseGlob("templates/*.html") if err != nil { log.Fatalln("Error loading templates:", err) } } 

Then, when I want to use one of the templates, I ask for it by name:

 t.ExecuteTemplate(w, "user.html", data) 
+12
source

From the template.go source code, the Execute function uses the lock, I'm new, it looks thread-safe, but it can be inefficient if you put an instance of the template on the card and try to reuse it if you need to execute many simultaneous requests:

 func (t *Template) Execute(wr io.Writer, data interface{}) (err error) { t.nameSpace.mu.Lock() if !t.escaped { if err = escapeTemplates(t, t.Name()); err != nil { t.escaped = true } } t.nameSpace.mu.Unlock() if err != nil { return } return t.text.Execute(wr, data) } 
0
source

All Articles