@ -10,88 +10,72 @@ import (
"git.phc.dm.unipi.it/phc/website/util"
)
type LoadTemplate interface {
Load ( t * template . Template ) ( * template . Template , error )
}
type File string
func ( file File ) Load ( t * template . Template ) ( * template . Template , error ) {
return t . ParseFiles ( string ( file ) )
}
type Pattern string
func ( pattern Pattern ) Load ( t * template . Template ) ( * template . Template , error ) {
return t . ParseGlob ( string ( pattern ) )
}
type CachedTemplate struct {
Load ers [ ] LoadTemplate
template * template . Template
LoadPatterns [ ] string
cachedTmpl * template . Template
}
func NewCacheTemplate ( load ers ... LoadTemplate ) * CachedTemplate {
func NewCacheTemplate ( loadPatterns ... string ) * CachedTemplate {
cachedTemplate := & CachedTemplate {
Load ers: load ers,
template: nil ,
LoadPatterns : loadPatterns ,
cachedTmpl : nil ,
}
template . Must ( cachedTemplate . Load ( template . New ( "" ) ) )
return cachedTemplate
}
func ( ct * CachedTemplate ) Load ( t * template . Template ) ( * template . Template , error ) {
if ct . template != nil {
return ct . template , nil
if ct . cachedTmpl != nil {
return ct . cachedTmpl , nil
}
ct . template = t
ct . cachedTmpl = t
for _ , loader := range ct . Load ers {
for _ , pattern := range ct . Load Patt ern s {
var err error
ct . template, err = loader . Load ( ct . template )
ct . cachedTmpl, err = ct . cachedTmpl . ParseGlob ( pattern )
if err != nil {
return nil , err
}
}
return ct . template , nil
return ct . cachedTmpl , nil
}
func ( ct * CachedTemplate ) Reload ( ) {
ct . template = nil
ct . cachedTmpl = nil
template . Must ( ct . Load ( nil ) )
}
func ( ct * CachedTemplate ) Template ( ) * template . Template {
return ct . template
return ct . cachedTmpl
}
// Renderer holds cached templates for rendering
type Renderer struct {
rootPath string
baseLoaders [ ] LoadTemplate
routes map [ string ] * CachedTemplate
loadPatterns [ ] string
templateCache map [ string ] * CachedTemplate
}
// NewRenderer constructs a template renderer with a base file
func NewRenderer ( rootPath string , load ers ... LoadTemplate ) * Renderer {
func NewRenderer ( rootPath string , load Patterns ... string ) * Renderer {
return & Renderer {
rootPath ,
load ers,
load Patt ern s,
map [ string ] * CachedTemplate { } ,
}
}
func ( r * Renderer ) Load ( name string ) * CachedTemplate {
cachedTemplate , present := r . routes [ name ]
cachedTemplate , present := r . templateCache [ name ]
if ! present {
loaders := [ ] LoadTemplate { }
loaders = append ( loaders , r . baseLoader s... )
loaders = append ( loaders , File ( path . Join ( r . rootPath , name ) ) )
loaders := [ ] string { }
loaders = append ( loaders , r . loadPattern s... )
loaders = append ( loaders , path . Join ( r . rootPath , name ) )
cachedTemplate = NewCacheTemplate ( loaders ... )
r . routes [ name ] = cachedTemplate
r . templateCache [ name ] = cachedTemplate
}
return cachedTemplate