pollo/lib/templates.go

63 lines
1.3 KiB
Go
Raw Permalink Normal View History

2023-05-18 20:04:55 -06:00
package lib
import (
"html/template"
"path/filepath"
"runtime"
2024-06-27 13:13:46 -06:00
templatefs "pollo/pages/templates"
2024-07-09 11:10:32 -06:00
"github.com/labstack/echo/v4"
2023-05-18 20:04:55 -06:00
)
2024-07-09 11:59:06 -06:00
type Error struct {
Code int
Message string
}
2024-07-09 11:10:32 -06:00
type TemplateData struct {
Props interface{}
IsLoggedIn bool
2024-07-09 11:59:06 -06:00
Error Error
2024-07-09 11:10:32 -06:00
}
2024-07-09 11:59:06 -06:00
func RenderTemplate(c echo.Context, layout string, partials []string, props interface{}, error Error) error {
2023-05-18 20:04:55 -06:00
// Get the name of the current file
_, filename, _, _ := runtime.Caller(1)
page := filepath.Base(filename)
page = page[:len(page)-len(filepath.Ext(page))] // remove the file extension
// Build the list of templates
templates := []string{
"layouts/" + layout + ".html",
page + ".html",
}
for _, partial := range partials {
templates = append(templates, "partials/"+partial+".html")
}
// Parse the templates
ts, err := template.ParseFS(templatefs.FS, templates...)
if err != nil {
2024-05-08 14:43:57 -06:00
LogError.Print(err.Error())
2023-05-18 20:04:55 -06:00
return err
}
2024-07-09 11:10:32 -06:00
// Wrap the props with the IsLoggedIn status
isLoggedIn := IsSignedIn(c)
templateData := TemplateData{
Props: props,
2024-07-09 11:59:06 -06:00
Error: error,
2024-07-09 11:10:32 -06:00
IsLoggedIn: isLoggedIn,
}
// Execute the layout template with the wrapped props
err = ts.ExecuteTemplate(c.Response().Writer, layout, templateData)
2023-05-18 20:04:55 -06:00
if err != nil {
2024-05-08 14:43:57 -06:00
LogError.Print(err.Error())
2023-05-18 20:04:55 -06:00
return err
}
return nil
}