forked from flosch/pongo2-addons
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filters.go
311 lines (256 loc) · 7.5 KB
/
filters.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
package pongo2addons
import (
"bytes"
"errors"
"fmt"
"math/rand"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/flosch/pongo2/v4"
"github.com/extemporalgenome/slug"
"github.com/flosch/go-humanize"
"github.com/russross/blackfriday/v2"
)
func init() {
rand.Seed(time.Now().UTC().UnixNano())
// Regulars
pongo2.RegisterFilter("slugify", filterSlugify)
pongo2.RegisterFilter("filesizeformat", filterFilesizeformat)
pongo2.RegisterFilter("truncatesentences", filterTruncatesentences)
pongo2.RegisterFilter("truncatesentences_html", filterTruncatesentencesHTML)
pongo2.RegisterFilter("random", filterRandom)
// Markup
pongo2.RegisterFilter("markdown", filterMarkdown)
// Humanize
pongo2.RegisterFilter("timeuntil", filterTimeuntilTimesince)
pongo2.RegisterFilter("timesince", filterTimeuntilTimesince)
pongo2.RegisterFilter("naturaltime", filterTimeuntilTimesince)
pongo2.RegisterFilter("naturalday", filterNaturalday)
pongo2.RegisterFilter("intcomma", filterIntcomma)
pongo2.RegisterFilter("ordinal", filterOrdinal)
}
func filterMarkdown(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsSafeValue(string(blackfriday.Run([]byte(in.String())))), nil
}
func filterSlugify(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsValue(slug.Slug(in.String())), nil
}
func filterFilesizeformat(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsValue(humanize.IBytes(uint64(in.Integer()))), nil
}
var filterTruncatesentencesRe = regexp.MustCompile(`(?U:.*[\w]{3,}.*([\d][\.!?][\D]|[\D][\.!?][\s]|[\n$]))`)
func filterTruncatesentences(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
count := param.Integer()
if count <= 0 {
return pongo2.AsValue(""), nil
}
sentencens := filterTruncatesentencesRe.FindAllString(strings.TrimSpace(in.String()), -1)
return pongo2.AsValue(strings.TrimSpace(strings.Join(sentencens[:min(count, len(sentencens))], ""))), nil
}
// Taken from pongo2/filters_builtin.go
func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func() bool, fn func(c rune, s int, idx int) int, finalize func()) {
vLen := len(value)
tagStack := make([]string, 0)
idx := 0
for idx < vLen && !cond() {
c, s := utf8.DecodeRuneInString(value[idx:])
if c == utf8.RuneError {
idx += s
continue
}
if c == '<' {
newOutput.WriteRune(c)
idx += s // consume "<"
if idx+1 < vLen {
if value[idx] == '/' {
// Close tag
newOutput.WriteString("/")
tag := ""
idx++ // consume "/"
for idx < vLen {
c2, size2 := utf8.DecodeRuneInString(value[idx:])
if c2 == utf8.RuneError {
idx += size2
continue
}
// End of tag found
if c2 == '>' {
idx++ // consume ">"
break
}
tag += string(c2)
idx += size2
}
if len(tagStack) > 0 {
// Ideally, the close tag is TOP of tag stack
// In malformed HTML, it must not be, so iterate through the stack and remove the tag
for i := len(tagStack) - 1; i >= 0; i-- {
if tagStack[i] == tag {
// Found the tag
tagStack[i] = tagStack[len(tagStack)-1]
tagStack = tagStack[:len(tagStack)-1]
break
}
}
}
newOutput.WriteString(tag)
newOutput.WriteString(">")
} else {
// Open tag
tag := ""
params := false
for idx < vLen {
c2, size2 := utf8.DecodeRuneInString(value[idx:])
if c2 == utf8.RuneError {
idx += size2
continue
}
newOutput.WriteRune(c2)
// End of tag found
if c2 == '>' {
idx++ // consume ">"
break
}
if !params {
if c2 == ' ' {
params = true
} else {
tag += string(c2)
}
}
idx += size2
}
// Add tag to stack
tagStack = append(tagStack, tag)
}
}
} else {
idx = fn(c, s, idx)
}
}
finalize()
for i := len(tagStack) - 1; i >= 0; i-- {
tag := tagStack[i]
// Close everything from the regular tag stack
newOutput.WriteString(fmt.Sprintf("</%s>", tag))
}
}
func filterTruncatesentencesHTML(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
count := param.Integer()
if count <= 0 {
return pongo2.AsValue(""), nil
}
value := in.String()
newLen := max(param.Integer(), 0)
newOutput := bytes.NewBuffer(nil)
sentencefilter := 0
filterTruncateHTMLHelper(value, newOutput, func() bool {
return sentencefilter >= newLen
}, func(_ rune, _ int, idx int) int {
// Get next word
wordFound := false
for idx < len(value) {
c2, size2 := utf8.DecodeRuneInString(value[idx:])
if c2 == utf8.RuneError {
idx += size2
continue
}
if c2 == '<' {
// HTML tag start, don't consume it
return idx
}
newOutput.WriteRune(c2)
idx += size2
if (c2 == '.' && !(idx+1 < len(value) && value[idx+1] >= '0' && value[idx+1] <= '9')) ||
c2 == '!' || c2 == '?' || c2 == '\n' {
// Sentence ends here, stop capturing it now
break
} else {
wordFound = true
}
}
if wordFound {
sentencefilter++
}
return idx
}, func() {})
return pongo2.AsSafeValue(newOutput.String()), nil
}
func filterRandom(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
if !in.CanSlice() {
return nil, &pongo2.Error{
Sender: "filter:random",
OrigError: errors.New("input is not sliceable"),
}
}
if in.Len() <= 0 {
return nil, &pongo2.Error{
Sender: "filter:random",
OrigError: errors.New("input slice is empty"),
}
}
return in.Index(rand.Intn(in.Len())), nil
}
func filterTimeuntilTimesince(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
basetime, isTime := in.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:timeuntil/timesince",
OrigError: errors.New("time-value is not a time.Time-instance"),
}
}
var paramtime time.Time
if !param.IsNil() {
paramtime, isTime = param.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:timeuntil/timesince",
OrigError: errors.New("time-parameter is not a time.Time-instance"),
}
}
} else {
paramtime = time.Now()
}
return pongo2.AsValue(humanize.TimeDuration(basetime.Sub(paramtime))), nil
}
func filterIntcomma(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsValue(humanize.Comma(int64(in.Integer()))), nil
}
func filterOrdinal(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
return pongo2.AsValue(humanize.Ordinal(in.Integer())), nil
}
func filterNaturalday(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
basetime, isTime := in.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:naturalday",
OrigError: errors.New("naturalday-value is not a time.Time-instance"),
}
}
var referenceTime time.Time
if !param.IsNil() {
referenceTime, isTime = param.Interface().(time.Time)
if !isTime {
return nil, &pongo2.Error{
Sender: "filter:naturalday",
OrigError: errors.New("naturalday-parameter is not a time.Time-instance"),
}
}
} else {
referenceTime = time.Now()
}
d := referenceTime.Sub(basetime) / time.Hour
switch {
case d >= 0 && d < 24:
// Today
return pongo2.AsValue("today"), nil
case d >= 24:
return pongo2.AsValue("yesterday"), nil
case d < 0 && d >= -24:
return pongo2.AsValue("tomorrow"), nil
}
// Default behaviour
return pongo2.ApplyFilter("naturaltime", in, param)
}