Skip to content

Instantly share code, notes, and snippets.

@muzfr7
Last active December 31, 2022 02:31
Show Gist options
  • Save muzfr7/4eeaf5f10c5273564f88f61b2cd69242 to your computer and use it in GitHub Desktop.
Save muzfr7/4eeaf5f10c5273564f88f61b2cd69242 to your computer and use it in GitHub Desktop.
A Go package to pre-compiles and register all the templates in a directory and it's subdirectories. FYI – this won't be a suitable approach if you have same file names in subdirectories!
package template
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/labstack/echo/v4"
)
// Template implements echo.Renderer interface.
type Template struct {
templates *template.Template
}
// NewTemplate pre-compiles and registers templates in given directory.
func NewTemplate(viewsDir, tmplFileExtension string) *Template {
return &Template{
templates: registerTemplates(viewsDir, tmplFileExtension),
}
}
// Render renders a template with given data.
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
if err := t.templates.ExecuteTemplate(w, name, data); err != nil {
fmt.Println(err)
return err
}
return nil
}
// registerTemplates is a helper func to walk the views directory
// and register each file with *template.Template.
func registerTemplates(viewsDir, tmplFileExtension string) *template.Template {
tpl := template.New("")
err := filepath.Walk(viewsDir, func(path string, info os.FileInfo, err error) error {
if strings.Contains(path, tmplFileExtension) {
_, err = tpl.ParseFiles(path)
if err != nil {
log.Println(err)
}
}
return err
})
if err != nil {
panic(err)
}
return tpl
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment