Created
October 31, 2020 20:56
-
-
Save KaiserWerk/54fbcaf41eb4d9c828431ab0f7c0bba9 to your computer and use it in GitHub Desktop.
Populate template map in Go
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
func populateTemplates(fm template.FuncMap) map[string]*template.Template { | |
result := make(map[string]*template.Template) | |
const basePath = "templates" | |
layout := template.Must(template.ParseFiles(basePath + "/_layout.html")).Funcs(fm) | |
dir, err := os.Open(basePath + "/content") | |
if err != nil { | |
panic("failed to open template base directory: " + err.Error()) | |
} | |
defer dir.Close() | |
fis, err := dir.Readdir(-1) | |
if err != nil { | |
panic("failed to contents of content directory: " + err.Error()) | |
} | |
for _, fi := range fis { | |
f, err := os.Open(basePath + "/content/" + fi.Name()) | |
if err != nil { | |
panic("failed to open template '" + fi.Name() + "': " + err.Error()) | |
} | |
content, err := ioutil.ReadAll(f) | |
if err != nil { | |
panic("failed to read content from file '" + fi.Name() + "': " + err.Error()) | |
} | |
_ = f.Close() | |
tmpl := template.Must(layout.Clone()) | |
_, err = tmpl.Parse(string(content)) | |
if err != nil { | |
panic("failed to parse contents of file '" + fi.Name() + "': " + err.Error()) | |
} | |
result[fi.Name()] = tmpl | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment