0
# Filters and Data Processing
1
2
Comprehensive collection of 54 built-in filters for data transformation including string processing, sequence manipulation, numeric operations, and object formatting. Filters can be chained and custom filters can be added to environments.
3
4
## Capabilities
5
6
### String Processing Filters
7
8
Filters for text manipulation, formatting, and HTML processing.
9
10
```python { .api }
11
def capitalize(s):
12
"""
13
Capitalize first character of string.
14
15
Parameters:
16
s: Input string
17
18
Returns:
19
str: String with first character capitalized
20
"""
21
22
def center(value, width=80):
23
"""
24
Center string in given width.
25
26
Parameters:
27
value: Input string
28
width: Total width (default: 80)
29
30
Returns:
31
str: Centered string
32
"""
33
34
def escape(s):
35
"""
36
HTML escape string (also available as 'e' filter).
37
38
Parameters:
39
s: Input string
40
41
Returns:
42
Markup: HTML-escaped string
43
"""
44
45
def forceescape(value):
46
"""
47
Force HTML escaping even for Markup objects.
48
49
Parameters:
50
value: Input value
51
52
Returns:
53
Markup: HTML-escaped value
54
"""
55
56
def format(value, *args, **kwargs):
57
"""
58
Format string using Python string formatting.
59
60
Parameters:
61
value: Format string
62
*args: Positional format arguments
63
**kwargs: Named format arguments
64
65
Returns:
66
str: Formatted string
67
"""
68
69
def indent(s, width=4, first=False, blank=False):
70
"""
71
Indent text by given width.
72
73
Parameters:
74
s: Input string
75
width: Indentation width (default: 4)
76
first: Indent first line (default: False)
77
blank: Indent blank lines (default: False)
78
79
Returns:
80
str: Indented text
81
"""
82
83
def lower(s):
84
"""
85
Convert string to lowercase.
86
87
Parameters:
88
s: Input string
89
90
Returns:
91
str: Lowercase string
92
"""
93
94
def replace(s, old, new, count=None):
95
"""
96
Replace substring occurrences.
97
98
Parameters:
99
s: Input string
100
old: Substring to replace
101
new: Replacement substring
102
count: Maximum replacements (default: all)
103
104
Returns:
105
str: String with replacements
106
"""
107
108
def safe(value):
109
"""
110
Mark string as safe (no HTML escaping).
111
112
Parameters:
113
value: Input value
114
115
Returns:
116
Markup: Safe markup object
117
"""
118
119
def string(object):
120
"""
121
Convert object to string.
122
123
Parameters:
124
object: Input object
125
126
Returns:
127
str: String representation
128
"""
129
130
def striptags(value):
131
"""
132
Strip HTML/XML tags from string.
133
134
Parameters:
135
value: Input string with HTML/XML
136
137
Returns:
138
str: String with tags removed
139
"""
140
141
def title(s):
142
"""
143
Convert string to title case.
144
145
Parameters:
146
s: Input string
147
148
Returns:
149
str: Title case string
150
"""
151
152
def trim(value):
153
"""
154
Strip leading and trailing whitespace.
155
156
Parameters:
157
value: Input string
158
159
Returns:
160
str: Trimmed string
161
"""
162
163
def truncate(s, length=255, killwords=False, end='...', leeway=None):
164
"""
165
Truncate string to specified length.
166
167
Parameters:
168
s: Input string
169
length: Maximum length (default: 255)
170
killwords: Cut in middle of words (default: False)
171
end: Truncation suffix (default: '...')
172
leeway: Extra characters allowed (default: None)
173
174
Returns:
175
str: Truncated string
176
"""
177
178
def upper(s):
179
"""
180
Convert string to uppercase.
181
182
Parameters:
183
s: Input string
184
185
Returns:
186
str: Uppercase string
187
"""
188
189
def urlencode(value):
190
"""
191
URL encode string.
192
193
Parameters:
194
value: Input string
195
196
Returns:
197
str: URL-encoded string
198
"""
199
200
def urlize(value, trim_url_limit=None, nofollow=False, target=None, rel=None):
201
"""
202
Convert URLs in text to clickable links.
203
204
Parameters:
205
value: Input text
206
trim_url_limit: Limit displayed URL length
207
nofollow: Add rel="nofollow" attribute
208
target: Link target attribute
209
rel: Link rel attribute
210
211
Returns:
212
Markup: Text with URLs converted to links
213
"""
214
215
def wordcount(s):
216
"""
217
Count words in string.
218
219
Parameters:
220
s: Input string
221
222
Returns:
223
int: Number of words
224
"""
225
226
def wordwrap(s, width=79, break_long_words=True, wrapstring=None):
227
"""
228
Wrap text to specified width.
229
230
Parameters:
231
s: Input string
232
width: Line width (default: 79)
233
break_long_words: Break long words (default: True)
234
wrapstring: Line break string (default: None)
235
236
Returns:
237
str: Wrapped text
238
"""
239
```
240
241
### Sequence and List Processing Filters
242
243
Filters for manipulating sequences, lists, and iterables.
244
245
```python { .api }
246
def batch(value, linecount, fill_with=None):
247
"""
248
Group items into batches of specified size.
249
250
Parameters:
251
value: Input sequence
252
linecount: Items per batch
253
fill_with: Value to fill incomplete batches
254
255
Returns:
256
Iterator: Batches of items
257
"""
258
259
def first(seq):
260
"""
261
Get first item from sequence.
262
263
Parameters:
264
seq: Input sequence
265
266
Returns:
267
Any: First item or Undefined if empty
268
"""
269
270
def groupby(value, attribute):
271
"""
272
Group items by attribute value.
273
274
Parameters:
275
value: Input sequence
276
attribute: Attribute name or callable to group by
277
278
Returns:
279
Iterator: Groups of (key, items) tuples
280
"""
281
282
def join(value, d='', attribute=None):
283
"""
284
Join sequence items with delimiter.
285
286
Parameters:
287
value: Input sequence
288
d: Delimiter string (default: '')
289
attribute: Item attribute to join (default: None)
290
291
Returns:
292
str: Joined string
293
"""
294
295
def last(seq):
296
"""
297
Get last item from sequence.
298
299
Parameters:
300
seq: Input sequence
301
302
Returns:
303
Any: Last item or Undefined if empty
304
"""
305
306
def length(obj):
307
"""
308
Get length/count of object (also available as 'count' filter).
309
310
Parameters:
311
obj: Input object
312
313
Returns:
314
int: Length of object
315
"""
316
317
def list(value):
318
"""
319
Convert value to list.
320
321
Parameters:
322
value: Input value
323
324
Returns:
325
list: List representation
326
"""
327
328
def random(seq):
329
"""
330
Select random item from sequence.
331
332
Parameters:
333
seq: Input sequence
334
335
Returns:
336
Any: Random item from sequence
337
"""
338
339
def reverse(value):
340
"""
341
Reverse sequence order.
342
343
Parameters:
344
value: Input sequence
345
346
Returns:
347
Iterator: Reversed sequence
348
"""
349
350
def slice(value, slices, fill_with=None):
351
"""
352
Slice sequence into multiple parts.
353
354
Parameters:
355
value: Input sequence
356
slices: Number of slices
357
fill_with: Value to fill incomplete slices
358
359
Returns:
360
Iterator: Sequence slices
361
"""
362
363
def sort(value, reverse=False, case_sensitive=False, attribute=None):
364
"""
365
Sort sequence items.
366
367
Parameters:
368
value: Input sequence
369
reverse: Sort in reverse order (default: False)
370
case_sensitive: Case-sensitive string sorting (default: False)
371
attribute: Item attribute to sort by (default: None)
372
373
Returns:
374
list: Sorted sequence
375
"""
376
377
def unique(value, case_sensitive=False, attribute=None):
378
"""
379
Get unique items from sequence.
380
381
Parameters:
382
value: Input sequence
383
case_sensitive: Case-sensitive uniqueness (default: False)
384
attribute: Item attribute for uniqueness (default: None)
385
386
Returns:
387
Iterator: Unique items
388
"""
389
```
390
391
### Numeric Processing Filters
392
393
Filters for numeric calculations and formatting.
394
395
```python { .api }
396
def abs(number):
397
"""
398
Get absolute value of number.
399
400
Parameters:
401
number: Input number
402
403
Returns:
404
number: Absolute value
405
"""
406
407
def float(value, default=0.0):
408
"""
409
Convert value to float.
410
411
Parameters:
412
value: Input value
413
default: Default value if conversion fails (default: 0.0)
414
415
Returns:
416
float: Float representation
417
"""
418
419
def int(value, default=0, base=10):
420
"""
421
Convert value to integer.
422
423
Parameters:
424
value: Input value
425
default: Default value if conversion fails (default: 0)
426
base: Number base for conversion (default: 10)
427
428
Returns:
429
int: Integer representation
430
"""
431
432
def round(value, precision=0, method='common'):
433
"""
434
Round number to specified precision.
435
436
Parameters:
437
value: Input number
438
precision: Decimal places (default: 0)
439
method: Rounding method ('common', 'ceil', 'floor') (default: 'common')
440
441
Returns:
442
number: Rounded number
443
"""
444
445
def sum(iterable, attribute=None, start=0):
446
"""
447
Sum numeric sequence.
448
449
Parameters:
450
iterable: Input sequence
451
attribute: Item attribute to sum (default: None)
452
start: Starting value (default: 0)
453
454
Returns:
455
number: Sum of values
456
"""
457
```
458
459
### Object and Data Processing Filters
460
461
Filters for object manipulation, attribute access, and data formatting.
462
463
```python { .api }
464
def attr(obj, name):
465
"""
466
Get object attribute by name.
467
468
Parameters:
469
obj: Input object
470
name: Attribute name
471
472
Returns:
473
Any: Attribute value
474
"""
475
476
def default(value, default_value='', boolean=False):
477
"""
478
Provide default value for undefined/empty values (also available as 'd' filter).
479
480
Parameters:
481
value: Input value
482
default_value: Default value to use (default: '')
483
boolean: Use boolean evaluation (default: False)
484
485
Returns:
486
Any: Original value or default
487
"""
488
489
def dictsort(value, case_sensitive=False, by='key', reverse=False):
490
"""
491
Sort dictionary by keys or values.
492
493
Parameters:
494
value: Input dictionary
495
case_sensitive: Case-sensitive sorting (default: False)
496
by: Sort by 'key' or 'value' (default: 'key')
497
reverse: Sort in reverse order (default: False)
498
499
Returns:
500
list: Sorted (key, value) tuples
501
"""
502
503
def filesizeformat(value, binary=False):
504
"""
505
Format file size in human-readable format.
506
507
Parameters:
508
value: Size in bytes
509
binary: Use binary (1024) or decimal (1000) base (default: False)
510
511
Returns:
512
str: Formatted size string
513
"""
514
515
def items(value):
516
"""
517
Get dictionary items as (key, value) pairs.
518
519
Parameters:
520
value: Input dictionary
521
522
Returns:
523
Iterator: (key, value) pairs
524
"""
525
526
def map(seq, func, *args, **kwargs):
527
"""
528
Apply filter to all items in sequence.
529
530
Parameters:
531
seq: Input sequence
532
func: Filter name or callable to apply
533
*args: Filter arguments
534
**kwargs: Filter keyword arguments
535
536
Returns:
537
Iterator: Filtered sequence
538
"""
539
540
def max(value, case_sensitive=False, attribute=None):
541
"""
542
Get maximum value from sequence.
543
544
Parameters:
545
value: Input sequence
546
case_sensitive: Case-sensitive comparison (default: False)
547
attribute: Item attribute to compare (default: None)
548
549
Returns:
550
Any: Maximum value
551
"""
552
553
def min(value, case_sensitive=False, attribute=None):
554
"""
555
Get minimum value from sequence.
556
557
Parameters:
558
value: Input sequence
559
case_sensitive: Case-sensitive comparison (default: False)
560
attribute: Item attribute to compare (default: None)
561
562
Returns:
563
Any: Minimum value
564
"""
565
566
def pprint(value, verbose=False):
567
"""
568
Pretty print value for debugging.
569
570
Parameters:
571
value: Input value
572
verbose: Include more detail (default: False)
573
574
Returns:
575
str: Pretty printed representation
576
"""
577
578
def reject(seq, func, *args, **kwargs):
579
"""
580
Reject items that pass test.
581
582
Parameters:
583
seq: Input sequence
584
func: Test name or callable
585
*args: Test arguments
586
**kwargs: Test keyword arguments
587
588
Returns:
589
Iterator: Items that failed test
590
"""
591
592
def rejectattr(seq, attribute, *args, **kwargs):
593
"""
594
Reject items by attribute test.
595
596
Parameters:
597
seq: Input sequence
598
attribute: Attribute name to test
599
*args: Test arguments
600
**kwargs: Test keyword arguments
601
602
Returns:
603
Iterator: Items that failed attribute test
604
"""
605
606
def select(seq, func, *args, **kwargs):
607
"""
608
Select items that pass test.
609
610
Parameters:
611
seq: Input sequence
612
func: Test name or callable
613
*args: Test arguments
614
**kwargs: Test keyword arguments
615
616
Returns:
617
Iterator: Items that passed test
618
"""
619
620
def selectattr(seq, attribute, *args, **kwargs):
621
"""
622
Select items by attribute test.
623
624
Parameters:
625
seq: Input sequence
626
attribute: Attribute name to test
627
*args: Test arguments
628
**kwargs: Test keyword arguments
629
630
Returns:
631
Iterator: Items that passed attribute test
632
"""
633
634
def tojson(value, indent=None):
635
"""
636
Convert value to JSON string.
637
638
Parameters:
639
value: Input value
640
indent: JSON indentation (default: None)
641
642
Returns:
643
str: JSON representation
644
"""
645
646
def xmlattr(d, autospace=True):
647
"""
648
Create XML attributes from dictionary.
649
650
Parameters:
651
d: Dictionary of attributes
652
autospace: Add leading space (default: True)
653
654
Returns:
655
Markup: XML attribute string
656
"""
657
```
658
659
## Usage Examples
660
661
### Chaining Filters
662
663
Filters can be chained together for complex data processing:
664
665
```python
666
# Template usage
667
{{ user.name | lower | replace(' ', '_') | truncate(20) }}
668
669
# Programmatic usage
670
env = Environment()
671
result = env.call_filter('truncate',
672
env.call_filter('replace',
673
env.call_filter('lower', 'John Doe Smith'),
674
' ', '_'
675
),
676
20
677
)
678
```
679
680
### Custom Filters
681
682
Add custom filters to environments:
683
684
```python
685
def custom_format_filter(value, format_type='default'):
686
if format_type == 'upper':
687
return str(value).upper()
688
elif format_type == 'title':
689
return str(value).title()
690
return str(value)
691
692
env = Environment()
693
env.filters['custom_format'] = custom_format_filter
694
695
# Use in templates: {{ name | custom_format('title') }}
696
```
697
698
## Types
699
700
```python { .api }
701
class FilterEnvironment:
702
"""
703
Filter execution environment providing context and utilities for filter functions.
704
705
Attributes:
706
environment: Jinja2 environment instance
707
context: Current template context (if available)
708
eval_ctx: Current evaluation context (if available)
709
"""
710
```