package components
import (
"context"
"github.com/gin-gonic/gin"
)
// CreateTemplateContext creates a new context with user information from Gin's context
func CreateTemplateContext(c *gin.Context) context.Context {
ctx := context.Background()
if userID, exists := c.Get("userID"); exists {
ctx = context.WithValue(ctx, "userID", userID)
}
if username, exists := c.Get("username"); exists {
ctx = context.WithValue(ctx, "username", username)
}
if email, exists := c.Get("email"); exists {
ctx = context.WithValue(ctx, "email", email)
}
if isAdmin, exists := c.Get("isAdmin"); exists {
ctx = context.WithValue(ctx, "isAdmin", isAdmin)
}
return ctx
}
templ Layout(title string) {
@LayoutWithContext(title, context.Background())
}
templ LayoutWithContext(title string, ctx context.Context) {
{ title } - GoMFT
if isLoggedIn(ctx) {
}
{ children... }
}
// Helper function to check if user is admin
func isAdmin(ctx context.Context) bool {
// Try as bool first
if admin, ok := ctx.Value("isAdmin").(bool); ok {
return admin
}
// Try as interface{} (from JWT claims)
if admin, ok := ctx.Value("isAdmin").(interface{}); ok {
if boolVal, ok := admin.(bool); ok {
return boolVal
}
}
return false
}
// Helper function to check if user is logged in
func isLoggedIn(ctx context.Context) bool {
// First try as uint
if userID, ok := ctx.Value("userID").(uint); ok && userID > 0 {
return true
}
// Then try as float64 (from JWT claims)
if userID, ok := ctx.Value("userID").(float64); ok && userID > 0 {
return true
}
return false
}
// Helper function to get user initial for avatar
func getUserInitial(ctx context.Context) string {
// Try as string first
if username, ok := ctx.Value("username").(string); ok && username != "" {
return string(username[0])
}
// Try as interface{} (from JWT claims)
if username, ok := ctx.Value("username").(interface{}); ok {
if strVal, ok := username.(string); ok && strVal != "" {
return string(strVal[0])
}
}
// Try email as fallback
if email, ok := ctx.Value("email").(string); ok && email != "" {
return string(email[0])
}
return "U"
}
// Helper function to get user email
func getUserEmail(ctx context.Context) string {
// Try as string first
if email, ok := ctx.Value("email").(string); ok && email != "" {
return email
}
// Try as interface{} (from JWT claims)
if email, ok := ctx.Value("email").(interface{}); ok {
if strVal, ok := email.(string); ok && strVal != "" {
return strVal
}
}
return "user@example.com"
}
// Helper function to get current year
func getCurrentYear() string {
return "2025"
}