68 lines
1.7 KiB
Go
68 lines
1.7 KiB
Go
package components
|
|
|
|
import (
|
|
"fmt"
|
|
"maps"
|
|
"runtime"
|
|
"strings"
|
|
|
|
"dk/internal/auth"
|
|
"dk/internal/csrf"
|
|
"dk/internal/middleware"
|
|
"dk/internal/router"
|
|
"dk/internal/session"
|
|
"dk/internal/template"
|
|
)
|
|
|
|
// RenderPage renders a page using the layout template with common data and additional custom data
|
|
func RenderPage(ctx router.Ctx, title, tmplPath string, additionalData map[string]any) error {
|
|
if template.Cache == nil {
|
|
return fmt.Errorf("template.Cache not initialized")
|
|
}
|
|
|
|
tmpl, err := template.Cache.Load(tmplPath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to load layout template: %w", err)
|
|
}
|
|
|
|
sess := ctx.UserValue("session").(*session.Session)
|
|
|
|
var m runtime.MemStats
|
|
runtime.ReadMemStats(&m)
|
|
|
|
data := map[string]any{
|
|
"_title": PageTitle(title),
|
|
"authenticated": auth.IsAuthenticated(ctx),
|
|
"csrf": csrf.HiddenField(ctx),
|
|
"_totaltime": middleware.GetRequestTime(ctx),
|
|
"_version": "1.0.0",
|
|
"_build": "dev",
|
|
"user": auth.GetCurrentUser(ctx),
|
|
"_memalloc": m.Alloc / 1024 / 1024,
|
|
"_errormsg": sess.GetFlashMessage("error"),
|
|
"_successmsg": sess.GetFlashMessage("success"),
|
|
}
|
|
|
|
maps.Copy(data, LeftAside(ctx))
|
|
maps.Copy(data, RightAside(ctx))
|
|
maps.Copy(data, additionalData)
|
|
|
|
tmpl.WriteTo(ctx, data)
|
|
return nil
|
|
}
|
|
|
|
// PageTitle returns a proper title for a rendered page. If an empty string
|
|
// is given, returns "Dragon Knight". If the provided title already has " - Dragon Knight"
|
|
// at the end, returns title as-is. Appends " - Dragon Knight" to title otherwise.
|
|
func PageTitle(title string) string {
|
|
if title == "" {
|
|
return "Dragon Knight"
|
|
}
|
|
|
|
if strings.HasSuffix(" - Dragon Knight", title) {
|
|
return title
|
|
}
|
|
|
|
return title + " - Dragon Knight"
|
|
}
|