-
-
Save AKosterin/280dc28ccb451156a9725f7c3e6bf669 to your computer and use it in GitHub Desktop.
Go's html/template with better subdirectory support.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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