goweb/template/html/loader.go

57 lines
1.1 KiB
Go
Raw Normal View History

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}
}