74 lines
1.3 KiB
Go
74 lines
1.3 KiB
Go
package helpers
|
|
|
|
import (
|
|
"html/template"
|
|
"net/http"
|
|
"synlotto-website/models"
|
|
|
|
"github.com/gorilla/csrf"
|
|
)
|
|
|
|
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
|
|
}
|
|
return b
|
|
},
|
|
"intVal": func(p *int) int {
|
|
if p == nil {
|
|
return 0
|
|
}
|
|
return *p
|
|
},
|
|
"inSlice": InSlice,
|
|
}
|
|
}
|
|
|
|
func TemplateContext(w http.ResponseWriter, r *http.Request) 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)
|
|
}
|
|
|
|
var currentUser *models.User
|
|
|
|
switch v := session.Values["user_id"].(type) {
|
|
case int:
|
|
currentUser = models.GetUserByID(v)
|
|
case int64:
|
|
currentUser = models.GetUserByID(int(v))
|
|
default:
|
|
currentUser = nil
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"CSRFField": csrf.TemplateField(r),
|
|
"Flash": flash,
|
|
"User": currentUser,
|
|
}
|
|
}
|
|
|
|
func InSlice(n int, list []int) bool {
|
|
for _, v := range list {
|
|
if v == n {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|