-
Notifications
You must be signed in to change notification settings - Fork 43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support for embed.FS #30
Comments
I'm currently using func (s *server) setupTemplates() {
getTemplateFileName := func(name string) string {
return fmt.Sprintf("%s/%s%s", templatesDir, name, templatesExtension)
}
// for each route its set of templates
tmpl := make(map[string]*template.Template)
tmpl["index"] = template.Must(template.ParseFS(web.Templates, getTemplateFileName("base"), getTemplateFileName("searchbar"), getTemplateFileName("index")))
tmpl["search"] = template.Must(template.ParseFS(web.Templates, getTemplateFileName("base"), getTemplateFileName("searchbar"), getTemplateFileName("table"), getTemplateFileName("search")))
r := multitemplate.NewRenderer()
for name, t := range tmpl {
r.Add(name, t)
}
s.router.HTMLRender = r
} func (s *server) handleIndex(c *gin.Context) {
// ...
c.HTML(http.StatusOK, "index", values)
} And its works like a charm ! |
For anyone that may need this in the future I was able to get this to work like so: //go:embed templates
var TemplateFS embed.FS
func LoadTemplates() multitemplate.Renderer {
templatesDir := "templates/"
r := multitemplate.NewRenderer()
funcMap := template.FuncMap{
"formatAsDate": func(t time.Time) string {
return t.Format("Jan 2, 2006")
},
}
layouts, err := fs.Glob(TemplateFS, templatesDir+"layouts/*.html")
if err != nil {
panic(err.Error())
}
partials, err := fs.Glob(TemplateFS, templatesDir+"partials/*.html")
if err != nil {
panic(err.Error())
}
views, err := fs.Glob(TemplateFS, templatesDir+"views/*.html")
if err != nil {
panic(err.Error())
}
// Generate our templates map from our layouts, partials, and views directories
for _, view := range views {
assets := []string{}
assets = append(assets, layouts...)
assets = append(assets, partials...)
files := append(assets, view)
// should be same name as the root file so that we don't get "incomplete" template error
tname := filepath.Base(files[0])
t := template.Must(template.New(tname).Funcs(funcMap).ParseFS(
TemplateFS,
files...,
))
fileName := filepath.Base(view)
templateName := strings.TrimSuffix(fileName, ".html")
r.Add(templateName, t)
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It would be really nice, to be able to use an embed.FS - on this way, the template files are inside the binary and it is not needed to ship it extra.
text/templates
andhtml/templates
support herefor.ParseFS(embed.FS, glob)
- see hereThe text was updated successfully, but these errors were encountered: