go-project-template/web/templates.go
Finn 4ebe6c7752 add auth
and some other improvements
2024-07-24 22:13:23 -07:00

60 lines
1.4 KiB
Go

package web
import (
"embed"
"fmt"
"html/template"
"io"
"io/fs"
"git.janky.solutions/finn/go-project-template/config"
echo "github.com/labstack/echo/v4"
)
var (
//go:embed templates
templatesFS embed.FS
templatesSubFS fs.FS
allTemplates *template.Template
funcs = template.FuncMap{
"version": func() string {
return fmt.Sprintf("%s %s", config.BuildInfo.Main.Path, config.Version)
},
}
//go:embed static
static embed.FS
Static fs.FS
)
func init() {
t := template.New("").Funcs(funcs)
var err error
templatesSubFS, err = fs.Sub(templatesFS, "templates")
if err != nil {
panic(err)
}
allTemplates, err = t.ParseFS(templatesSubFS, "*")
if err != nil {
panic(err)
}
Static, err = fs.Sub(static, "static")
if err != nil {
panic(err)
}
}
type Template struct {
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
// Why does it work like this? because go's templating system doesn't handle multiple templates extending from a common base well
// just doing it normally causes every template to render the same (the import form, at time of writing, probably the last template alphabetically)
// https://stackoverflow.com/a/69244593/21894038
tmpl := template.Must(allTemplates.Clone())
tmpl = template.Must(tmpl.ParseFS(templatesSubFS, name))
return tmpl.ExecuteTemplate(w, name, data)
}