-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathroute_dom_context.go
92 lines (83 loc) · 2.08 KB
/
route_dom_context.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package fir
import (
"strings"
"text/template"
"github.com/goccy/go-json"
"github.com/tidwall/gjson"
)
func newFirFuncMap(ctx RouteContext, errs map[string]any) template.FuncMap {
return template.FuncMap{
"fir": func() *RouteDOMContext {
return newRouteDOMContext(ctx, errs)
},
}
}
func newRouteDOMContext(ctx RouteContext, errs map[string]any) *RouteDOMContext {
var urlPath string
var name string
if ctx.request != nil {
urlPath = ctx.request.URL.Path
}
if ctx.route != nil {
name = ctx.route.appName
}
if errs == nil {
errs = make(map[string]any)
}
return &RouteDOMContext{
URLPath: urlPath,
Name: name,
Development: ctx.route.developmentMode,
errors: errs,
}
}
// RouteDOMContext is a struct that holds route context data and is passed to the template
type RouteDOMContext struct {
Name string
Development bool
URLPath string
errors map[string]any
}
// ActiveRoute returns the class if the route is active
func (rc *RouteDOMContext) ActiveRoute(path, class string) string {
if rc.URLPath == path {
return class
}
return ""
}
// NotActive returns the class if the route is not active
func (rc *RouteDOMContext) NotActiveRoute(path, class string) string {
if rc.URLPath != path {
return class
}
return ""
}
// Error can be used to lookup an error by name
// Example: {{fir.Error "myevent.field"}} will return the error for the field myevent.field
// Example: {{fir.Error "myevent" "field"}} will return the error for the event myevent.field
// It can be used in conjunction with ctx.FieldError to get the error for a field
func (rc *RouteDOMContext) Error(paths ...string) any {
if len(rc.errors) == 0 {
return nil
}
data, _ := json.Marshal(rc.errors)
val := gjson.GetBytes(data, getErrorLookupPath(paths...)).Value()
_, ok := val.(map[string]any)
if ok {
return nil
}
return val
}
func getErrorLookupPath(paths ...string) string {
path := ""
if len(paths) == 0 {
path = "default"
} else {
for _, p := range paths {
p = strings.Trim(p, ".")
path += p + "."
}
}
path = strings.Trim(path, ".")
return path
}