Skip to content

Instantly share code, notes, and snippets.

@marconi
Created September 14, 2013 15:02
Show Gist options
  • Save marconi/6562719 to your computer and use it in GitHub Desktop.
Save marconi/6562719 to your computer and use it in GitHub Desktop.
...
var tplCache *template.Template
...
func init() {
CacheTemplates()
}
func CacheTemplates() {
tplFiles := make(map[string]map[string]string)
tplIncludes := make(map[string]map[string]string)
walk := func(path string, f os.FileInfo, err error) error {
if !f.IsDir() {
baseName := filepath.Base(path)
tplInfo := map[string]string{
"path": path,
"base": baseName,
}
tplFiles[baseName] = tplInfo
}
return nil
}
scanTpls := func() {
// scan all template files first
if err := filepath.Walk(templateRoot, walk); err != nil {
panic(err)
}
// load included templates first
for _, tplInfo := range tplFiles {
if tplInfo["base"][0] == '_' {
tplIncludes[tplInfo["base"]] = tplInfo
}
}
// remove include templates from list of templates
for baseName, _ := range tplFiles {
if _, ok := tplIncludes[baseName]; ok {
delete(tplFiles, baseName)
}
}
}
loadIncludeTpls := func() {
for baseName, tplInclude := range tplIncludes {
_, err := tplCache.New(baseName).ParseFiles(tplInclude["path"])
if err != nil {
panic(err)
}
}
}
loadRegularTpls := func() {
for baseName, tplInfo := range tplFiles {
_, err := tplCache.New(baseName).ParseFiles(tplInfo["path"])
if err != nil {
panic(err)
}
}
}
refreshTpls := func() {
tplCache = template.New("devstream")
loadIncludeTpls()
loadRegularTpls()
}
scanTpls()
refreshTpls()
// spawn template watcher
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
go func() {
log.Println("spawning template watcher...")
for {
select {
case <-watcher.Event:
refreshTpls()
case err := <-watcher.Error:
fmt.Println("error watching templates:", err)
}
}
}()
err = watcher.Watch(templateRoot)
if err != nil {
panic(err)
}
}
// profit!
tpl := tplCache.Lookup("index.html")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment