-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathfilters_builtin.go
More file actions
2542 lines (2261 loc) · 69 KB
/
filters_builtin.go
File metadata and controls
2542 lines (2261 loc) · 69 KB
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package pongo2
/* Filters that won't be added:
----------------------------
get_static_prefix (reason: web-framework specific)
pprint (reason: python-specific)
static (reason: web-framework specific)
*/
/*
Notable Django behavior references for filter implementations:
---------------------------------------------------------------
- title: Django uses a custom algorithm that capitalizes after any non-letter/digit
character, then fixes apostrophe and digit cases with regex.
Django ref: django/utils/text.py capfirst(), re.sub for apostrophe/digit.
- center: Padding bias for odd margins follows Python's str.center():
left = marg/2 + (marg & width & 1). Both odd → extra on left, else right.
Django ref: django/template/defaultfilters.py center() → str.center().
- slugify: Django preserves underscores in slugs. Underscores are NOT stripped.
Django ref: django/utils/text.py slugify().
- filesizeformat: Uses non-breaking space (U+00A0) between number and unit,
singular "byte" (not "bytes") for exactly 1 byte, and "-" prefix for negatives.
Django ref: django/template/defaultfilters.py filesizeformat().
- timesince/timeuntil: Uses calendar-based month/year arithmetic (not fixed
365/30 approximations). Shows only adjacent time units. Returns "0 minutes"
for reversed dates.
Django ref: django/utils/timesince.py.
- linebreaks: Groups text into paragraphs split by double newlines. Within
paragraphs, single newlines become <br />. The paragraph algorithm is:
split by 2+ newlines → each paragraph gets <p>...</p>.
Django ref: django/utils/html.py linebreaks().
- unordered_list: Uses tab indentation with depth starting at 1. Items are
separated by newlines. Nested sublists get <ul>/<li> on separate lines.
Django ref: django/template/defaultfilters.py unordered_list() → list_formatter().
- escapejs: Escapes characters 0x00-0x1F, \, ', ", `, <, >, &, =, -, ;,
U+2028, U+2029 to \uXXXX format (uppercase hex in Django, lowercase in Go).
Django ref: django/utils/html.py _js_escapes table.
- wordwrap: Wraps at character column width (not word count). Uses word-boundary
breaking (long words are not split). Preserves existing newlines.
Normalizes \r\n and \r to \n before processing. Verified against Django 4.2.
Django ref: django/utils/text.py wrap().
- floatformat: Negative arg means "display N decimal places unless the result
would be all zeros." Positive arg always shows exactly N places.
Django ref: django/template/defaultfilters.py floatformat().
- forloop: Django's forloop has counter, counter0, revcounter, revcounter0,
first, last, parentloop — but NOT a .length attribute.
Django ref: django/template/defaulttags.py ForNode.
- urlencode: Uses Go's url.QueryEscape. Django difference: Django uses
urllib.parse.quote(safe='/') which encodes spaces as %20 and preserves /.
Go's url.QueryEscape encodes spaces as + and encodes / as %2F.
- iriencode: Uses Go's url.QueryEscape for non-IRI characters. Django
difference: Django's iri_to_uri() uses urllib.parse.quote() which encodes
spaces as %20. Go's url.QueryEscape encodes spaces as +.
- truncatewords: Verified against Django 4.2 with script. Matches Django's
Truncator(value).words(length, truncate=" …") — space before ellipsis is
intentional.
- truncatechars: Verified against Django 4.2 with script.
- truncatechars_html / truncatewords_html: Returns AsSafeValue() to prevent
double-escaping of preserved HTML tags. Django difference: Django uses
is_safe=True which preserves input safety status; pongo2 unconditionally
marks output as safe. This is more user-friendly for HTML-producing filters.
- escapejs: Verified against Django 4.2 with script. Uses lowercase hex
(\u000d) instead of Django's uppercase (\u000D) — functionally equivalent.
- phone2numeric: Verified against Django 4.2 with script.
- divisibleby: Verified against Django 4.2 with script.
- yesno: Verified against Django 4.2 with script.
- templatetag: Verified against Django 4.2 with script.
Intentional differences from Django:
- stringformat: Uses Go fmt format verbs instead of Python % formatting.
- date: Uses Go time formatting (reference time: Mon Jan 2 15:04:05 MST 2006)
instead of Django's PHP-style format characters.
- now tag: Uses Go time formatting instead of Django format characters.
- lorem tag: Uses static pre-defined paragraphs; Django generates random text
from a word list.
- firstof tag: Does not support "as variable_name" syntax (feature gap).
*/
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/rand"
"net/url"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
"golang.org/x/text/unicode/norm"
)
func mustRegisterFilter(name string, fn FilterFunction) {
if err := registerFilterBuiltin(name, fn); err != nil {
panic(err)
}
}
// htmlEscapeReplacer is a pre-compiled replacer for HTML escaping.
// Using a single Replacer is more efficient than multiple strings.Replace calls
// because it processes the string in a single pass.
var htmlEscapeReplacer = strings.NewReplacer(
"&", "&",
">", ">",
"<", "<",
`"`, """,
"'", "'",
)
// stripTagsIteratively applies tag-stripping regex patterns iteratively until convergence.
// This handles obfuscated tags like "<sc<script>ript>" which become "<script>" after first pass.
// Returns an error if stripping doesn't converge within maxIterations.
func stripTagsIteratively(s string, patterns []*regexp.Regexp, maxIterations int, filterName string) (string, error) {
for i := range maxIterations {
prev := s
for _, re := range patterns {
s = re.ReplaceAllString(s, "")
}
if s == prev {
return strings.TrimSpace(s), nil
}
if i == maxIterations-1 {
return "", &Error{
Sender: filterName,
OrigError: fmt.Errorf("tag stripping did not converge after max iterations (%d); input may be maliciously crafted", maxIterations),
}
}
}
return strings.TrimSpace(s), nil
}
// addslashesReplacer is a pre-compiled replacer for adding slashes.
var addslashesReplacer = strings.NewReplacer(
`\`, `\\`,
`"`, `\"`,
"'", `\'`,
)
func init() {
mustRegisterFilter("escape", filterEscape)
mustRegisterFilter("e", filterEscape) // alias of `escape`
mustRegisterFilter("safe", filterSafe)
mustRegisterFilter("escapejs", filterEscapejs)
mustRegisterFilter("add", filterAdd)
mustRegisterFilter("addslashes", filterAddslashes)
mustRegisterFilter("capfirst", filterCapfirst)
mustRegisterFilter("center", filterCenter)
mustRegisterFilter("cut", filterCut)
mustRegisterFilter("date", filterDate)
mustRegisterFilter("default", filterDefault)
mustRegisterFilter("default_if_none", filterDefaultIfNone)
mustRegisterFilter("divisibleby", filterDivisibleby)
mustRegisterFilter("first", filterFirst)
mustRegisterFilter("floatformat", filterFloatformat)
mustRegisterFilter("get_digit", filterGetdigit)
mustRegisterFilter("iriencode", filterIriencode)
mustRegisterFilter("join", filterJoin)
mustRegisterFilter("last", filterLast)
mustRegisterFilter("length", filterLength)
mustRegisterFilter("length_is", filterLengthis)
mustRegisterFilter("linebreaks", filterLinebreaks)
mustRegisterFilter("linebreaksbr", filterLinebreaksbr)
mustRegisterFilter("linenumbers", filterLinenumbers)
mustRegisterFilter("ljust", filterLjust)
mustRegisterFilter("lower", filterLower)
mustRegisterFilter("make_list", filterMakelist)
mustRegisterFilter("phone2numeric", filterPhone2numeric)
mustRegisterFilter("pluralize", filterPluralize)
mustRegisterFilter("random", filterRandom)
mustRegisterFilter("removetags", filterRemovetags)
mustRegisterFilter("rjust", filterRjust)
mustRegisterFilter("slice", filterSlice)
mustRegisterFilter("split", filterSplit)
mustRegisterFilter("stringformat", filterStringformat)
mustRegisterFilter("striptags", filterStriptags)
mustRegisterFilter("time", filterDate) // time uses filterDate (same golang-format)
mustRegisterFilter("title", filterTitle)
mustRegisterFilter("truncatechars", filterTruncatechars)
mustRegisterFilter("truncatechars_html", filterTruncatecharsHTML)
mustRegisterFilter("truncatewords", filterTruncatewords)
mustRegisterFilter("truncatewords_html", filterTruncatewordsHTML)
mustRegisterFilter("upper", filterUpper)
mustRegisterFilter("urlencode", filterUrlencode)
mustRegisterFilter("urlize", filterUrlize)
mustRegisterFilter("urlizetrunc", filterUrlizetrunc)
mustRegisterFilter("wordcount", filterWordcount)
mustRegisterFilter("wordwrap", filterWordwrap)
mustRegisterFilter("yesno", filterYesno)
mustRegisterFilter("timesince", filterTimesince)
mustRegisterFilter("timeuntil", filterTimeuntil)
mustRegisterFilter("dictsort", filterDictsort)
mustRegisterFilter("dictsortreversed", filterDictsortReversed)
mustRegisterFilter("unordered_list", filterUnorderedList)
mustRegisterFilter("slugify", filterSlugify)
mustRegisterFilter("filesizeformat", filterFilesizeformat)
mustRegisterFilter("safeseq", filterSafeseq)
mustRegisterFilter("escapeseq", filterEscapeseq)
mustRegisterFilter("json_script", filterJSONScript)
mustRegisterFilter("float", filterFloat) // pongo-specific
mustRegisterFilter("integer", filterInteger) // pongo-specific
}
const ellipsis = "…"
func filterTruncatecharsHelper(s string, newLen int) string {
runes := []rune(s)
if newLen < len(runes) {
if newLen >= 1 {
// Use proper ellipsis character (…) like Django does
return string(runes[:newLen-1]) + ellipsis
}
// Django returns just the ellipsis for length <= 0
return ellipsis
}
return string(runes)
}
// countHTMLTextRunes counts the number of text runes (non-tag characters)
// in an HTML string. This is used to determine whether truncation is needed.
func countHTMLTextRunes(value string) int {
count := 0
inTag := false
for _, c := range value {
if c == '<' {
inTag = true
continue
}
if c == '>' {
inTag = false
continue
}
if !inTag {
count++
}
}
return count
}
func filterTruncateHTMLHelper(value string, newOutput *bytes.Buffer, cond func() bool, fn func(c rune, s int, idx int) int, finalize func()) {
vLen := len(value)
var tagStack []string
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
var tag strings.Builder
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.WriteString(string(c2))
}
}
idx += size2
}
// Add tag to stack
tagStack = append(tagStack, tag.String())
}
}
} 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
fmt.Fprintf(newOutput, "</%s>", tag)
}
}
// filterTruncatechars truncates a string if it is longer than the specified number
// of characters. Truncated strings will end with a translatable ellipsis character ("…").
// The ellipsis counts towards the character limit.
//
// Usage:
//
// {{ "Joel is a slug"|truncatechars:7 }}
//
// Output: "Joel i…"
//
// {{ "Hi"|truncatechars:5 }}
//
// Output: "Hi" (no truncation needed)
func filterTruncatechars(in *Value, param *Value) (*Value, error) {
s := in.String()
newLen := param.Integer()
return AsValue(filterTruncatecharsHelper(s, newLen)), nil
}
// filterTruncatecharsHTML truncates a string if it is longer than the specified number
// of characters, similar to truncatechars but aware of HTML tags. Any tags that are
// opened in the string and not closed before the truncation point are closed immediately
// after the truncation. HTML tags are not counted towards the character limit.
// Truncated strings will end with an ellipsis character ("…") which counts towards the limit.
// Newlines in the HTML content will be preserved.
//
// Verified against Django 4.2 with script.
// Django difference: Returns AsSafeValue() to prevent double-escaping of preserved
// HTML tags. Django uses is_safe=True (preserves input safety status) instead.
//
// Usage:
//
// {{ "<p>Joel is a slug</p>"|truncatechars_html:7 }}
//
// Output: "<p>Joel i…</p>"
func filterTruncatecharsHTML(in *Value, param *Value) (*Value, error) {
value := in.String()
maxLen := param.Integer()
// Count the total number of text runes (excluding HTML tags) to determine
// whether truncation is actually needed. Without this, we would always
// reserve space for the ellipsis and truncate even when the full text
// fits within the limit.
totalTextRunes := countHTMLTextRunes(value)
if totalTextRunes <= maxLen {
// No truncation needed - return original value with tags intact
return AsSafeValue(value), nil
}
// Reserve one character position for the ellipsis
newLen := max(maxLen-1, 0)
var newOutput bytes.Buffer
textcounter := 0
filterTruncateHTMLHelper(value, &newOutput, func() bool {
return textcounter >= newLen
}, func(c rune, s int, idx int) int {
textcounter++
newOutput.WriteRune(c)
return idx + s
}, func() {
if textcounter >= newLen {
newOutput.WriteString(ellipsis)
}
})
return AsSafeValue(newOutput.String()), nil
}
// filterTruncatewords truncates a string after a certain number of words.
// If truncated, a space and Unicode ellipsis (" …") is appended.
//
// Django reference: django/utils/text.py Truncator.words(truncate=" …")
// Verified against Django 4.2 with script — space before ellipsis is intentional.
//
// Usage:
//
// {{ "Hello beautiful world"|truncatewords:2 }}
//
// Output: "Hello beautiful …"
//
// {{ "Hi"|truncatewords:5 }}
//
// Output: "Hi"
func filterTruncatewords(in *Value, param *Value) (*Value, error) {
words := strings.Fields(in.String())
n := param.Integer()
if n <= 0 {
return AsValue(""), nil
}
nlen := min(len(words), n)
out := make([]string, 0, nlen)
for i := range nlen {
out = append(out, words[i])
}
if n < len(words) {
out = append(out, "\u2026")
}
return AsValue(strings.Join(out, " ")), nil
}
// filterTruncatewordsHTML truncates a string after a certain number of words,
// preserving HTML tags. HTML tags are not counted towards the word limit.
// If truncated, an ellipsis ("...") is appended. Open HTML tags are properly closed.
//
// Verified against Django 4.2 with script.
// Django difference: Returns AsSafeValue() to prevent double-escaping of preserved
// HTML tags. Django uses is_safe=True (preserves input safety status) instead.
//
// Usage:
//
// {{ "<p>Hello beautiful world</p>"|truncatewords_html:2 }}
//
// Output: "<p>Hello beautiful …</p>"
func filterTruncatewordsHTML(in *Value, param *Value) (*Value, error) {
value := in.String()
newLen := max(param.Integer(), 0)
newOutput := bytes.NewBuffer(nil)
wordcounter := 0
filterTruncateHTMLHelper(value, newOutput, func() bool {
return wordcounter >= 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 == ' ' || c2 == '.' || c2 == ',' || c2 == ';' {
// Word ends here, stop capturing it now
break
} else {
wordFound = true
}
}
if wordFound {
wordcounter++
}
return idx
}, func() {
if wordcounter >= newLen {
newOutput.WriteString("\u2026")
}
})
return AsSafeValue(newOutput.String()), nil
}
// filterEscape escapes a string's HTML characters. Specifically, it makes these replacements:
// - < is converted to <
// - > is converted to >
// - ' (single quote) is converted to '
// - " (double quote) is converted to "
// - & is converted to &
//
// The filter is also available under the alias "e".
//
// Usage:
//
// {{ "<script>alert('XSS')</script>"|escape }}
//
// Output: "<script>alert('XSS')</script>"
func filterEscape(in *Value, param *Value) (*Value, error) {
return AsSafeValue(htmlEscapeReplacer.Replace(in.String())), nil
}
// filterSafe marks a string as safe, meaning it will not be HTML-escaped when
// rendered. Use this filter when you know the content is safe and should be
// rendered as-is (e.g., pre-sanitized HTML content).
//
// Usage:
//
// {{ "<b>Bold text</b>"|safe }}
//
// Output: "<b>Bold text</b>"
//
// Without safe filter (when autoescape is on):
//
// {{ "<b>Bold text</b>" }}
//
// Output: "<b>Bold text</b>"
func filterSafe(in *Value, param *Value) (*Value, error) {
return in, nil // nothing to do here, just to keep track of the safe application
}
// filterEscapejs escapes characters for safe use in JavaScript string literals.
// It converts special characters to their Unicode escape sequences (\uXXXX format).
//
// Characters that are escaped (matching Django's behavior):
// - Backslash, quotes: \ ' " `
// - HTML special chars: < > & = -
// - Semicolon: ;
// - Control characters: 0x00-0x1F, 0x7F, 0x80-0x9F
// - Line separators: U+2028, U+2029
//
// Additionally, pongo2 interprets \r and \n escape sequences in the input
// and converts them to their Unicode escapes (\u000D and \u000A).
//
// Note: This filter escapes backticks, making it safe for JavaScript template
// literals as well as single/double quoted strings.
//
// Django reference: django/utils/html.py _js_escapes table.
// Verified against Django 4.2 with script.
// Django difference: uses lowercase hex (\u000d) vs Django's uppercase (\u000D) —
// functionally equivalent per JavaScript spec.
//
// Usage:
//
// <script>var name = "{{ name|escapejs }}";</script>
//
// With name = "John's \"Quote\"":
//
// Output: <script>var name = "John\u0027s \u0022Quote\u0022";</script>
func filterEscapejs(in *Value, param *Value) (*Value, error) {
sin := in.String()
var b bytes.Buffer
// Use index-based iteration to handle pongo2-specific \r and \n escape sequences
idx := 0
for idx < len(sin) {
c, size := utf8.DecodeRuneInString(sin[idx:])
if c == utf8.RuneError && size == 1 {
// Invalid UTF-8, skip
idx += size
continue
}
// Handle pongo2-specific escape sequences: \r -> \u000D, \n -> \u000A
if c == '\\' && idx+size < len(sin) {
nextByte := sin[idx+size]
switch nextByte {
case 'r':
b.WriteString(`\u000D`)
idx += size + 1
continue
case 'n':
b.WriteString(`\u000A`)
idx += size + 1
continue
}
}
switch {
// Characters that must be escaped for JavaScript string safety
case c == '\\':
b.WriteString(`\u005C`)
case c == '\'':
b.WriteString(`\u0027`)
case c == '"':
b.WriteString(`\u0022`)
case c == '`':
b.WriteString(`\u0060`)
case c == '<':
b.WriteString(`\u003C`)
case c == '>':
b.WriteString(`\u003E`)
case c == '&':
b.WriteString(`\u0026`)
case c == '=':
b.WriteString(`\u003D`)
case c == '-':
b.WriteString(`\u002D`)
case c == ';':
b.WriteString(`\u003B`)
case c == '\u2028': // Line separator
b.WriteString(`\u2028`)
case c == '\u2029': // Paragraph separator
b.WriteString(`\u2029`)
// Control characters (0x00-0x1F, 0x7F, 0x80-0x9F)
case c <= 0x1F, c == 0x7F, (c >= 0x80 && c <= 0x9F):
fmt.Fprintf(&b, `\u%04X`, c)
default:
b.WriteRune(c)
}
idx += size
}
return AsSafeValue(b.String()), nil
}
// filterAdd adds the argument to the value. Works with numbers (integers and floats)
// and strings (concatenation).
//
// Usage with numbers:
//
// {{ 5|add:3 }}
//
// Output: 8
//
// {{ 3.5|add:2.1 }}
//
// Output: 5.600000
//
// Usage with strings:
//
// {{ "Hello "|add:"World" }}
//
// Output: "Hello World"
func filterAdd(in *Value, param *Value) (*Value, error) {
if in.IsNumber() && param.IsNumber() {
if in.IsFloat() || param.IsFloat() {
return AsValue(in.Float() + param.Float()), nil
}
return AsValue(in.Integer() + param.Integer()), nil
}
// If in/param is not a number, we're relying on the
// Value's String() conversion and just add them both together
return AsValue(in.String() + param.String()), nil
}
// filterAddslashes adds backslashes before quotes and backslashes.
// Useful for escaping strings in CSV or JavaScript contexts.
//
// Usage:
//
// {{ "I'm using \"pongo2\""|addslashes }}
//
// Output: "I\'m using \"pongo2\""
func filterAddslashes(in *Value, param *Value) (*Value, error) {
return AsValue(addslashesReplacer.Replace(in.String())), nil
}
// filterCut removes all occurrences of the argument from the string.
//
// Usage:
//
// {{ "Hello World"|cut:" " }}
//
// Output: "HelloWorld"
//
// {{ "String with spaces"|cut:" " }}
//
// Output: "Stringwithspaces"
func filterCut(in *Value, param *Value) (*Value, error) {
return AsValue(strings.ReplaceAll(in.String(), param.String(), "")), nil
}
// filterLength returns the length of the value. Works with strings (character count),
// slices, arrays, and maps.
//
// Usage with strings:
//
// {{ "Hello"|length }}
//
// Output: 5
//
// Usage with lists:
//
// {% set items = ["a", "b", "c"] %}{{ items|length }}
//
// Output: 3
func filterLength(in *Value, param *Value) (*Value, error) {
return AsValue(in.Len()), nil
}
// filterLengthis returns true if the value's length equals the argument.
// Useful in conditional expressions.
//
// Usage:
//
// {% if items|length_is:3 %}Exactly 3 items{% endif %}
//
// {{ "Hello"|length_is:5 }}
//
// Output: True
func filterLengthis(in *Value, param *Value) (*Value, error) {
return AsValue(in.Len() == param.Integer()), nil
}
// filterDefault returns the argument if the value is falsy (empty string, 0,
// nil, false, empty slice/map). Otherwise returns the original value.
//
// Usage:
//
// {{ name|default:"Guest" }}
//
// If name is empty or not set, output: "Guest"
// If name is "John", output: "John"
//
// {{ 0|default:42 }}
//
// Output: 42
func filterDefault(in *Value, param *Value) (*Value, error) {
if !in.IsTrue() {
return param, nil
}
return in, nil
}
// filterDefaultIfNone returns the argument only if the value is nil.
// Unlike "default", this only triggers on nil values, not on other falsy values
// like 0, false, or empty strings.
//
// Usage:
//
// {{ value|default_if_none:"N/A" }}
//
// If value is nil, output: "N/A"
// If value is 0, output: 0 (unlike default filter)
// If value is "", output: "" (unlike default filter)
func filterDefaultIfNone(in *Value, param *Value) (*Value, error) {
if in.IsNil() {
return param, nil
}
return in, nil
}
// filterDivisibleby returns true if the value is divisible by the argument.
// Returns false if the argument is 0 (to avoid division by zero).
//
// Usage:
//
// {{ 21|divisibleby:7 }}
//
// Output: True
//
// {% if forloop.Counter|divisibleby:2 %}even{% else %}odd{% endif %}
func filterDivisibleby(in *Value, param *Value) (*Value, error) {
if param.Integer() == 0 {
return AsValue(false), nil
}
return AsValue(in.Integer()%param.Integer() == 0), nil
}
// filterFirst returns the first element of a slice/array or the first character
// of a string. Returns an empty string if the input is empty.
//
// Usage with list:
//
// {{ ["a", "b", "c"]|first }}
//
// Output: "a"
//
// Usage with string:
//
// {{ "Hello"|first }}
//
// Output: "H"
func filterFirst(in *Value, param *Value) (*Value, error) {
if in.CanSlice() && in.Len() > 0 {
return in.Index(0), nil
}
return AsValue(""), nil
}
const maxFloatFormatDecimals = 1000
// filterFloatformat formats a floating-point number with a specified number of
// decimal places. If the argument is negative or omitted, trailing zeros are removed.
//
// Usage:
//
// {{ 3.14159|floatformat:2 }}
//
// Output: "3.14"
//
// {{ 3.0|floatformat:2 }}
//
// Output: "3.00"
//
// {{ 3.0|floatformat:-2 }}
//
// Output: "3" (trailing zeros removed)
//
// {{ 3.14159|floatformat }}
//
// Output: "3.1" (default: -1 decimal, trailing zeros removed)
func filterFloatformat(in *Value, param *Value) (*Value, error) {
val := in.Float()
decimals := -1
if !param.IsNil() {
// Any argument provided?
decimals = param.Integer()
}
// if the argument is not a number (e. g. empty), the default
// behaviour is trim the result
trim := !param.IsNumber()
if decimals <= 0 {
// argument is negative or zero, so we
// want the output being trimmed
decimals = -decimals
trim = true
}
if trim {
// Remove zeroes
if float64(int(val)) == val {
return AsValue(in.Integer()), nil
}
}
if decimals > maxFloatFormatDecimals {
return nil, &Error{
Sender: "filter:floatformat",
OrigError: fmt.Errorf("filter floatformat doesn't support more than %v decimals", maxFloatFormatDecimals),
}
}
return AsValue(strconv.FormatFloat(val, 'f', decimals, 64)), nil
}
// filterGetdigit returns the digit at position N from the right (1-indexed).
// Position 1 is the rightmost digit. Returns the original value if N is out of range.
//
// Usage:
//
// {{ 123456789|get_digit:1 }}
//
// Output: 9 (rightmost digit)
//
// {{ 123456789|get_digit:2 }}
//
// Output: 8
//
// {{ 123456789|get_digit:9 }}
//
// Output: 1 (leftmost digit)
func filterGetdigit(in *Value, param *Value) (*Value, error) {
i := param.Integer()
if i <= 0 {
return in, nil
}
// Convert to string and validate it contains only digits (and optional leading minus).
// This matches Django's behavior: int(value) must succeed, then we work with
// the absolute value's digit string.
s := in.String()
// Determine the start of digits (skip optional leading minus sign)
start := 0
if len(s) > 0 && s[0] == '-' {
start = 1
}
digits := s[start:]
// Verify all remaining characters are digits; if not, return original value
for j := 0; j < len(digits); j++ {
if digits[j] < '0' || digits[j] > '9' {
return in, nil
}
}
l := len(digits)
if l == 0 || i > l {
return in, nil
}
return AsValue(int(digits[l-i] - '0')), nil
}
const filterIRIChars = "/#%[]=:;$&()+,!?*@'~"
// filterIriencode encodes an IRI (Internationalized Resource Identifier) for safe
// use in URLs. Unlike urlencode, it preserves characters that are valid in IRIs
// (such as /, #, %, etc.) while encoding other special characters using
// Go's url.QueryEscape.
//
// Django difference: Django's iri_to_uri() uses urllib.parse.quote() which encodes
// spaces as %20. Go's url.QueryEscape encodes spaces as +. Both are valid
// percent-encoding for query strings, but %20 is preferred in path segments.
//
// Usage:
//
// {{ "https://example.com/path with spaces"|iriencode }}
//
// Output: "https://example.com/path+with+spaces"
//
// {{ "/search?q=hello world"|iriencode }}
//
// Output: "/search?q=hello+world"
func filterIriencode(in *Value, param *Value) (*Value, error) {
var b strings.Builder
sin := in.String()
for _, r := range sin {
if strings.ContainsRune(filterIRIChars, r) {
b.WriteRune(r)
} else {
b.WriteString(url.QueryEscape(string(r)))
}
}
return AsValue(b.String()), nil
}
// filterJoin joins a list with the given separator string. For strings, each
// character is joined with the separator.
//
// Usage with list:
//
// {{ ["apple", "banana", "cherry"]|join:", " }}
//
// Output: "apple, banana, cherry"
//
// Usage with string:
//
// {{ "abc"|join:"-" }}
//
// Output: "a-b-c"
func filterJoin(in *Value, param *Value) (*Value, error) {
if !in.CanSlice() {