template: add layout loading API

This commit is contained in:
wpetit 2020-01-24 13:09:16 +01:00
parent bbcb571772
commit 18f2ffaaa9
3 changed files with 43 additions and 14 deletions

1
go.mod
View File

@ -3,6 +3,7 @@ module gitlab.com/wpetit/goweb
go 1.12
require (
github.com/davecgh/go-spew v1.1.0
github.com/go-chi/chi v4.0.2+incompatible
github.com/go-playground/locales v0.12.1 // indirect
github.com/go-playground/universal-translator v0.16.0 // indirect

View File

@ -6,7 +6,7 @@ import "gitlab.com/wpetit/goweb/service"
// the HTML template service implementation
func ServiceProvider(templateDir string, funcs ...OptionFunc) service.Provider {
templateService := NewTemplateService(funcs...)
err := templateService.LoadTemplates(templateDir)
err := templateService.LoadTemplatesDir(templateDir)
return func(container *service.Container) (interface{}, error) {
if err != nil {
return nil, err

View File

@ -3,6 +3,7 @@ package html
import (
"fmt"
"html/template"
"io/ioutil"
"net/http"
"path/filepath"
@ -16,35 +17,62 @@ type TemplateService struct {
helpers template.FuncMap
}
// LoadTemplates loads the templates used by the service
func (t *TemplateService) LoadTemplates(templatesDir string) error {
func (t *TemplateService) LoadLayout(name string, layout string, blocks []string) error {
tmpl := template.New(name)
tmpl.Funcs(t.helpers)
layouts, err := filepath.Glob(filepath.Join(templatesDir, "layouts", "*.tmpl"))
for _, b := range blocks {
if _, err := tmpl.Parse(b); err != nil {
return err
}
}
tmpl, err := tmpl.Parse(layout)
if err != nil {
return err
}
blocks, err := filepath.Glob(filepath.Join(templatesDir, "blocks", "*.tmpl"))
t.templates[name] = tmpl
return nil
}
// LoadTemplatesDir loads the templates used by the service
func (t *TemplateService) LoadTemplatesDir(templatesDir string) error {
layoutFiles, err := filepath.Glob(filepath.Join(templatesDir, "layouts", "*.tmpl"))
if err != nil {
return err
}
// Generate our templates map from our layouts/ and blocks/ directories
for _, layout := range layouts {
blockFiles, err := filepath.Glob(filepath.Join(templatesDir, "blocks", "*.tmpl"))
if err != nil {
return err
}
var err error
files := append(blocks, layout)
blockTemplates := make([]string, 0, len(blockFiles))
tmpl := template.New("")
tmpl.Funcs(t.helpers)
tmpl, err = tmpl.ParseFiles(files...)
for _, f := range blockFiles {
templateData, err := ioutil.ReadFile(f)
if err != nil {
return err
}
t.templates[filepath.Base(layout)] = tmpl
blockTemplates = append(blockTemplates, string(templateData))
}
// 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 := t.LoadLayout(templateName, string(templateData), blockTemplates); err != nil {
return err
}
}
return nil