- Introduced helpers.LoadTemplateFiles() for consistent layout + topbar rendering - Replaced repeated template.ParseFiles() calls across handlers - Created generic RenderError(w, r, statusCode) helper - Replaced old Render403 with flexible RenderError - Updated AdminOnly middleware to render 403 errors with context - Added 500.html template for graceful panic fallback - Prepared structure for future error codes (404, 429, etc.)
110 lines
2.2 KiB
Go
110 lines
2.2 KiB
Go
package helpers
|
|
|
|
import (
|
|
"html/template"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"synlotto-website/models"
|
|
|
|
"github.com/gorilla/csrf"
|
|
)
|
|
|
|
func TemplateContext(w http.ResponseWriter, r *http.Request, data models.TemplateData) map[string]interface{} {
|
|
session, _ := GetSession(w, r)
|
|
|
|
var flash string
|
|
if f, ok := session.Values["flash"].(string); ok {
|
|
flash = f
|
|
delete(session.Values, "flash")
|
|
session.Save(r, w)
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"CSRFField": csrf.TemplateField(r),
|
|
"Flash": flash,
|
|
"User": data.User,
|
|
"IsAdmin": data.IsAdmin,
|
|
"NotificationCount": data.NotificationCount,
|
|
"Notifications": data.Notifications,
|
|
"MessageCount": data.MessageCount,
|
|
"Messages": data.Messages,
|
|
}
|
|
}
|
|
|
|
func TemplateFuncs() template.FuncMap {
|
|
return template.FuncMap{
|
|
"plus1": func(i int) int { return i + 1 },
|
|
"minus1": func(i int) int {
|
|
if i > 1 {
|
|
return i - 1
|
|
}
|
|
return 0
|
|
},
|
|
"mul": func(a, b int) int { return a * b },
|
|
"add": func(a, b int) int { return a + b },
|
|
"min": func(a, b int) int {
|
|
if a < b {
|
|
return a
|
|
} else {
|
|
return b
|
|
}
|
|
},
|
|
"intVal": func(p *int) int {
|
|
if p == nil {
|
|
return 0
|
|
}
|
|
return *p
|
|
},
|
|
"inSlice": InSlice,
|
|
"lower": lower,
|
|
"rangeClass": rangeClass,
|
|
}
|
|
}
|
|
|
|
func LoadTemplateFiles(name string, files ...string) *template.Template {
|
|
shared := []string{
|
|
"templates/layout.html",
|
|
"templates/topbar.html",
|
|
}
|
|
all := append(shared, files...)
|
|
|
|
return template.Must(template.New(name).Funcs(TemplateFuncs()).ParseFiles(all...))
|
|
}
|
|
|
|
func SetFlash(w http.ResponseWriter, r *http.Request, message string) {
|
|
session, _ := GetSession(w, r)
|
|
session.Values["flash"] = message
|
|
session.Save(r, w)
|
|
}
|
|
|
|
func InSlice(n int, list []int) bool {
|
|
for _, v := range list {
|
|
if v == n {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func lower(input string) string {
|
|
return strings.ToLower(input)
|
|
}
|
|
|
|
func rangeClass(n int) string {
|
|
switch {
|
|
case n >= 1 && n <= 9:
|
|
return "01-09"
|
|
case n >= 10 && n <= 19:
|
|
return "10-19"
|
|
case n >= 20 && n <= 29:
|
|
return "20-29"
|
|
case n >= 30 && n <= 39:
|
|
return "30-39"
|
|
case n >= 40 && n <= 49:
|
|
return "40-49"
|
|
default:
|
|
return "50-plus"
|
|
}
|
|
}
|