forked from go-catupiry/catu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
view.go
224 lines (185 loc) · 5.24 KB
/
view.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package bolo
import (
"bytes"
"fmt"
"html/template"
"io"
"io/ioutil"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"github.com/go-bolo/bolo/pagination"
"github.com/labstack/echo/v4"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
// type tplWrapper struct {
// Ctx *RequestContext
// }
type TemplateCTX struct {
EchoContext echo.Context
Ctx interface{}
Record interface{}
Records interface{}
}
type TemplateRenderer struct {
templates *template.Template
}
func (t *TemplateRenderer) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
switch v := data.(type) {
case int:
// v is an int here, so e.g. v + 1 is possible.
fmt.Printf("Integer: %v", v)
case float64:
// v is a float64 here, so e.g. v + 1.0 is possible.
fmt.Printf("Float64: %v", v)
case string:
// v is a string here, so e.g. v + " Yeah!" is possible.
fmt.Printf("String: %v", v)
default:
htmlContext := data.(*TemplateCTX)
htmlContext.EchoContext = c
logrus.WithFields(logrus.Fields{
"name": name,
"htmlContext": htmlContext,
"len templates": len(t.templates.Templates()),
}).Debug("Render")
ctx := htmlContext.Ctx.(*RequestContext)
var contentBuffer bytes.Buffer
err := ctx.RenderTemplate(&contentBuffer, name, htmlContext)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": fmt.Sprintf("%+v\n", errors.Wrap(err, "bolo.theme.Render error on render template")),
"name": name,
}).Error("bolo.theme.Render error on execute template")
return c.JSON(http.StatusInternalServerError,
&BaseErrorResponse{
Messages: []BaseErrorResponseMessage{{Status: "error", Message: "Error on render template, check if the template exists and if the data is correct. Template: " + name}},
})
}
ctx.Content = template.HTML(contentBuffer.String())
var layoutBuffer bytes.Buffer
err = ctx.RenderTemplate(&layoutBuffer, ctx.Layout, htmlContext)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"name": name,
"theme": ctx.Theme,
"layout": ctx.Layout,
}).Error("bolo.theme.Render error on execute layout template")
return err
}
ctx.Content = template.HTML(layoutBuffer.String())
return ctx.RenderTemplate(w, "html", htmlContext)
}
return nil
}
func findAndParseTemplates(rootDir string, funcMap template.FuncMap) (*template.Template, error) {
cleanRoot := filepath.Clean(rootDir)
pfx := len(cleanRoot) + 1
root := template.New("")
err := filepath.Walk(cleanRoot, func(path string, info os.FileInfo, e1 error) error {
if info != nil && !info.IsDir() && strings.HasSuffix(path, ".html") {
if e1 != nil {
return e1
}
b, e2 := ioutil.ReadFile(path)
if e2 != nil {
return e2
}
name := path[pfx:]
name = strings.Replace(name, ".html", "", 1)
t := root.New(name).Funcs(funcMap)
_, e2 = t.Parse(string(b))
if e2 != nil {
return e2
}
}
return nil
})
return root, err
}
func renderPager(ctx *RequestContext, r *pagination.Pager, queryString string) template.HTML {
var htmlBuffer bytes.Buffer
logrus.WithFields(logrus.Fields{
"count": r.Count,
"Pager": string(r.ToJSON()),
}).Debug("paginate params")
if r.Count == 0 {
return template.HTML("")
}
currentUrl := r.CurrentUrl
queryParamsStr := ""
if queryString != "" {
queryParamsStr += "&" + queryString
}
pageCountFloat := float64(r.Count) / float64(r.Limit)
pageCount := int64(math.Ceil(pageCountFloat))
totalLinks := (r.MaxLinks * 2) + 1
startInPage := int64(1)
endInPage := pageCount
if pageCount == 0 {
return template.HTML("")
}
if totalLinks < pageCount {
if r.MaxLinks+2 < r.Page {
startInPage = r.Page - r.MaxLinks
r.FirstPath = currentUrl + "?page=1" + queryParamsStr
r.FirstNumber = "1"
r.HasMoreBefore = true
}
if (r.MaxLinks + r.Page + 1) < pageCount {
endInPage = r.MaxLinks + r.Page
r.LastPath = currentUrl + "?page=" + strconv.FormatInt(pageCount, 10) + queryParamsStr
r.LastNumber = strconv.FormatInt(pageCount, 10)
r.HasMoreAfter = true
}
}
// Each link
for i := startInPage; i <= endInPage; i++ {
number := strconv.FormatInt(i, 10)
var link = pagination.Link{
Path: currentUrl + "?page=" + number + queryParamsStr,
Number: number,
}
if i == r.Page {
link.IsActive = true
}
// logrus.WithFields(logrus.Fields{
// "i": i,
// "Page": r.Page,
// }).Debug("Calculing afterEach")
r.Links = append(r.Links, link)
}
if r.Page > 1 {
r.HasPrevius = true
number := strconv.FormatInt(r.Page-1, 10)
r.PreviusPath = currentUrl + "?page=" + number + queryParamsStr
r.PreviusNumber = number
}
if r.Page < pageCount {
r.HasNext = true
number := strconv.FormatInt(r.Page+1, 10)
r.NextPath = currentUrl + "?page=" + number + queryParamsStr
r.NextNumber = number
}
// logrus.WithFields(logrus.Fields{
// "pagger": string(r.ToJSON()),
// "startInPage": startInPage,
// "endInPage": endInPage,
// }).Debug("Calculing end")
err := ctx.RenderTemplate(&htmlBuffer, "components/paginate", TemplateCTX{
Ctx: &r,
})
if err != nil {
logrus.WithFields(logrus.Fields{
"pagger": &r,
"error": err,
"theme": ctx.Theme,
}).Error("theme.paginate Error on render template")
}
return template.HTML(htmlBuffer.String())
}