From f748a7023430bb58ce2653982997185a6d0b79fc Mon Sep 17 00:00:00 2001 From: Peter Takacs Date: Fri, 11 Oct 2024 22:43:25 +0200 Subject: [PATCH] Enhanced template handling --- inertia.go | 38 ++++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/inertia.go b/inertia.go index 1d5fb50..53e1803 100644 --- a/inertia.go +++ b/inertia.go @@ -13,14 +13,15 @@ import ( // Inertia type. type Inertia struct { - url string - rootTemplate string - version string - sharedProps map[string]interface{} - sharedFuncMap template.FuncMap - templateFS fs.FS - ssrURL string - ssrClient *http.Client + url string + rootTemplate string + version string + sharedProps map[string]interface{} + sharedFuncMap template.FuncMap + parsedTemplate *template.Template + templateFS fs.FS + ssrURL string + ssrClient *http.Client } // New function. @@ -231,13 +232,30 @@ func (i *Inertia) isInertiaRequest(r *http.Request) bool { } func (i *Inertia) createRootTemplate() (*template.Template, error) { + if i.parsedTemplate != nil { + return i.parsedTemplate, nil + } + ts := template.New(filepath.Base(i.rootTemplate)).Funcs(i.sharedFuncMap) + var tpl *template.Template + var err error + if i.templateFS != nil { - return ts.ParseFS(i.templateFS, i.rootTemplate) + tpl, err = ts.ParseFS(i.templateFS, i.rootTemplate) + if err != nil { + return nil, err + } + } else { + tpl, err = ts.ParseFiles(i.rootTemplate) + if err != nil { + return nil, err + } } - return ts.ParseFiles(i.rootTemplate) + i.parsedTemplate = tpl + + return i.parsedTemplate, nil } func (i *Inertia) ssr(page *Page) (*Ssr, error) {