package main
import (
"fmt"
"html/template"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/labstack/echo"
)
// Reset reads all the templates
func (t *Template) Reset() {
pagesPath := `templates/pages/`
componentsPath := `templates/components/*.gohtml`
if t.templates == nil {
t.templates = make(map[string]*template.Template)
}
pages := []string{}
err := filepath.Walk(pagesPath, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
if !f.IsDir() {
pages = append(pages, path)
}
return nil
})
if err != nil {
log.Fatal(err)
}
components, err := filepath.Glob(componentsPath)
if err != nil {
log.Fatal(err)
}
for _, layout := range pages {
files := append(components, layout)
name := path.Base(removeExt(layout))
t.templates[name] = template.Must(template.New(``).ParseFiles(files...))
}
}
// Render echo Render func
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
tmpl, ok := t.templates[name]
if !ok {
return fmt.Errorf("template '%s' not found", name)
}
return tmpl.ExecuteTemplate(w, "base", data)
}
func removeExt(s string) string {
return strings.TrimSuffix(s, path.Ext(s))
}