goweb/template/html/loader.go
William Petit 985ce3eba3 template/html: refactor template loading
Allow customization of the template loading process by providing a
Loader implementation.

Allow auto-reloading of templates in development mode.
2020-07-07 09:01:04 +02:00

57 lines
1.1 KiB
Go

package html
import (
"io/ioutil"
"path/filepath"
)
type Loader interface {
Load(*TemplateService) error
}
type DirectoryLoader struct {
rootDir string
}
func (l *DirectoryLoader) Load(srv *TemplateService) error {
blockFiles, err := filepath.Glob(filepath.Join(l.rootDir, "blocks", "*.tmpl"))
if err != nil {
return err
}
for _, f := range blockFiles {
blockContent, err := ioutil.ReadFile(f)
if err != nil {
return err
}
blockName := filepath.Base(f)
srv.AddBlock(blockName, string(blockContent))
}
layoutFiles, err := filepath.Glob(filepath.Join(l.rootDir, "layouts", "*.tmpl"))
if err != nil {
return err
}
// Generate our templates map from our layouts/ and blocks/ directories
for _, f := range layoutFiles {
templateData, err := ioutil.ReadFile(f)
if err != nil {
return err
}
templateName := filepath.Base(f)
if err := srv.LoadLayout(templateName, string(templateData)); err != nil {
return err
}
}
return nil
}
func NewDirectoryLoader(rootDir string) *DirectoryLoader {
return &DirectoryLoader{rootDir}
}