Skip to content

Instantly share code, notes, and snippets.

@AKosterin
Forked from iwinux/gist:5578188
Created February 20, 2017 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AKosterin/280dc28ccb451156a9725f7c3e6bf669 to your computer and use it in GitHub Desktop.
Save AKosterin/280dc28ccb451156a9725f7c3e6bf669 to your computer and use it in GitHub Desktop.
Go's html/template with better subdirectory support.
package templates
import(
"html/template"
"io"
"os"
"strings"
"path/filepath"
)
var templates map[string]*template.Template
func init() {
selfPath, err := filepath.Abs(os.Args[0])
if err != nil { panic(err) }
selfDir := filepath.Dir(selfPath)
collectTemplates(filepath.Join(selfDir, "templates"))
}
func Render(out io.Writer, name string, data interface{}) {
if tmpl, ok := templates[name]; ok {
err := tmpl.Execute(out, data)
if err != nil { panic(err) }
}
}
func collectTemplates(tmplDir string) {
templates = make(map[string]*template.Template)
prefix := tmplDir + "/"
base, err := template.ParseFiles(filepath.Join(tmplDir, "base.html"))
if err != nil { panic(err) }
filepath.Walk(tmplDir, func(path string, info os.FileInfo, err error) error {
if isTemplateFile(info) {
key := strings.TrimPrefix(path, prefix)
clone, err := base.Clone()
if err != nil { panic(err) }
_, err = clone.ParseFiles(path)
if err != nil { panic(err) }
templates[key] = clone
}
return nil
})
}
func isTemplateFile(info os.FileInfo) bool {
if info.Mode().IsRegular() {
name := info.Name()
if name != "base.html" && strings.HasSuffix(name, ".html") {
return true
}
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment