A very fast and expressive template engine for Python applications
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
Filters for text manipulation, formatting, and HTML processing.
def capitalize(s):
"""
Capitalize first character of string.
Parameters:
s: Input string
Returns:
str: String with first character capitalized
"""
def center(value, width=80):
"""
Center string in given width.
Parameters:
value: Input string
width: Total width (default: 80)
Returns:
str: Centered string
"""
def escape(s):
"""
HTML escape string (also available as 'e' filter).
Parameters:
s: Input string
Returns:
Markup: HTML-escaped string
"""
def forceescape(value):
"""
Force HTML escaping even for Markup objects.
Parameters:
value: Input value
Returns:
Markup: HTML-escaped value
"""
def format(value, *args, **kwargs):
"""
Format string using Python string formatting.
Parameters:
value: Format string
*args: Positional format arguments
**kwargs: Named format arguments
Returns:
str: Formatted string
"""
def indent(s, width=4, first=False, blank=False):
"""
Indent text by given width.
Parameters:
s: Input string
width: Indentation width (default: 4)
first: Indent first line (default: False)
blank: Indent blank lines (default: False)
Returns:
str: Indented text
"""
def lower(s):
"""
Convert string to lowercase.
Parameters:
s: Input string
Returns:
str: Lowercase string
"""
def replace(s, old, new, count=None):
"""
Replace substring occurrences.
Parameters:
s: Input string
old: Substring to replace
new: Replacement substring
count: Maximum replacements (default: all)
Returns:
str: String with replacements
"""
def safe(value):
"""
Mark string as safe (no HTML escaping).
Parameters:
value: Input value
Returns:
Markup: Safe markup object
"""
def string(object):
"""
Convert object to string.
Parameters:
object: Input object
Returns:
str: String representation
"""
def striptags(value):
"""
Strip HTML/XML tags from string.
Parameters:
value: Input string with HTML/XML
Returns:
str: String with tags removed
"""
def title(s):
"""
Convert string to title case.
Parameters:
s: Input string
Returns:
str: Title case string
"""
def trim(value):
"""
Strip leading and trailing whitespace.
Parameters:
value: Input string
Returns:
str: Trimmed string
"""
def truncate(s, length=255, killwords=False, end='...', leeway=None):
"""
Truncate string to specified length.
Parameters:
s: Input string
length: Maximum length (default: 255)
killwords: Cut in middle of words (default: False)
end: Truncation suffix (default: '...')
leeway: Extra characters allowed (default: None)
Returns:
str: Truncated string
"""
def upper(s):
"""
Convert string to uppercase.
Parameters:
s: Input string
Returns:
str: Uppercase string
"""
def urlencode(value):
"""
URL encode string.
Parameters:
value: Input string
Returns:
str: URL-encoded string
"""
def urlize(value, trim_url_limit=None, nofollow=False, target=None, rel=None):
"""
Convert URLs in text to clickable links.
Parameters:
value: Input text
trim_url_limit: Limit displayed URL length
nofollow: Add rel="nofollow" attribute
target: Link target attribute
rel: Link rel attribute
Returns:
Markup: Text with URLs converted to links
"""
def wordcount(s):
"""
Count words in string.
Parameters:
s: Input string
Returns:
int: Number of words
"""
def wordwrap(s, width=79, break_long_words=True, wrapstring=None):
"""
Wrap text to specified width.
Parameters:
s: Input string
width: Line width (default: 79)
break_long_words: Break long words (default: True)
wrapstring: Line break string (default: None)
Returns:
str: Wrapped text
"""Filters for manipulating sequences, lists, and iterables.
def batch(value, linecount, fill_with=None):
"""
Group items into batches of specified size.
Parameters:
value: Input sequence
linecount: Items per batch
fill_with: Value to fill incomplete batches
Returns:
Iterator: Batches of items
"""
def first(seq):
"""
Get first item from sequence.
Parameters:
seq: Input sequence
Returns:
Any: First item or Undefined if empty
"""
def groupby(value, attribute):
"""
Group items by attribute value.
Parameters:
value: Input sequence
attribute: Attribute name or callable to group by
Returns:
Iterator: Groups of (key, items) tuples
"""
def join(value, d='', attribute=None):
"""
Join sequence items with delimiter.
Parameters:
value: Input sequence
d: Delimiter string (default: '')
attribute: Item attribute to join (default: None)
Returns:
str: Joined string
"""
def last(seq):
"""
Get last item from sequence.
Parameters:
seq: Input sequence
Returns:
Any: Last item or Undefined if empty
"""
def length(obj):
"""
Get length/count of object (also available as 'count' filter).
Parameters:
obj: Input object
Returns:
int: Length of object
"""
def list(value):
"""
Convert value to list.
Parameters:
value: Input value
Returns:
list: List representation
"""
def random(seq):
"""
Select random item from sequence.
Parameters:
seq: Input sequence
Returns:
Any: Random item from sequence
"""
def reverse(value):
"""
Reverse sequence order.
Parameters:
value: Input sequence
Returns:
Iterator: Reversed sequence
"""
def slice(value, slices, fill_with=None):
"""
Slice sequence into multiple parts.
Parameters:
value: Input sequence
slices: Number of slices
fill_with: Value to fill incomplete slices
Returns:
Iterator: Sequence slices
"""
def sort(value, reverse=False, case_sensitive=False, attribute=None):
"""
Sort sequence items.
Parameters:
value: Input sequence
reverse: Sort in reverse order (default: False)
case_sensitive: Case-sensitive string sorting (default: False)
attribute: Item attribute to sort by (default: None)
Returns:
list: Sorted sequence
"""
def unique(value, case_sensitive=False, attribute=None):
"""
Get unique items from sequence.
Parameters:
value: Input sequence
case_sensitive: Case-sensitive uniqueness (default: False)
attribute: Item attribute for uniqueness (default: None)
Returns:
Iterator: Unique items
"""Filters for numeric calculations and formatting.
def abs(number):
"""
Get absolute value of number.
Parameters:
number: Input number
Returns:
number: Absolute value
"""
def float(value, default=0.0):
"""
Convert value to float.
Parameters:
value: Input value
default: Default value if conversion fails (default: 0.0)
Returns:
float: Float representation
"""
def int(value, default=0, base=10):
"""
Convert value to integer.
Parameters:
value: Input value
default: Default value if conversion fails (default: 0)
base: Number base for conversion (default: 10)
Returns:
int: Integer representation
"""
def round(value, precision=0, method='common'):
"""
Round number to specified precision.
Parameters:
value: Input number
precision: Decimal places (default: 0)
method: Rounding method ('common', 'ceil', 'floor') (default: 'common')
Returns:
number: Rounded number
"""
def sum(iterable, attribute=None, start=0):
"""
Sum numeric sequence.
Parameters:
iterable: Input sequence
attribute: Item attribute to sum (default: None)
start: Starting value (default: 0)
Returns:
number: Sum of values
"""Filters for object manipulation, attribute access, and data formatting.
def attr(obj, name):
"""
Get object attribute by name.
Parameters:
obj: Input object
name: Attribute name
Returns:
Any: Attribute value
"""
def default(value, default_value='', boolean=False):
"""
Provide default value for undefined/empty values (also available as 'd' filter).
Parameters:
value: Input value
default_value: Default value to use (default: '')
boolean: Use boolean evaluation (default: False)
Returns:
Any: Original value or default
"""
def dictsort(value, case_sensitive=False, by='key', reverse=False):
"""
Sort dictionary by keys or values.
Parameters:
value: Input dictionary
case_sensitive: Case-sensitive sorting (default: False)
by: Sort by 'key' or 'value' (default: 'key')
reverse: Sort in reverse order (default: False)
Returns:
list: Sorted (key, value) tuples
"""
def filesizeformat(value, binary=False):
"""
Format file size in human-readable format.
Parameters:
value: Size in bytes
binary: Use binary (1024) or decimal (1000) base (default: False)
Returns:
str: Formatted size string
"""
def items(value):
"""
Get dictionary items as (key, value) pairs.
Parameters:
value: Input dictionary
Returns:
Iterator: (key, value) pairs
"""
def map(seq, func, *args, **kwargs):
"""
Apply filter to all items in sequence.
Parameters:
seq: Input sequence
func: Filter name or callable to apply
*args: Filter arguments
**kwargs: Filter keyword arguments
Returns:
Iterator: Filtered sequence
"""
def max(value, case_sensitive=False, attribute=None):
"""
Get maximum value from sequence.
Parameters:
value: Input sequence
case_sensitive: Case-sensitive comparison (default: False)
attribute: Item attribute to compare (default: None)
Returns:
Any: Maximum value
"""
def min(value, case_sensitive=False, attribute=None):
"""
Get minimum value from sequence.
Parameters:
value: Input sequence
case_sensitive: Case-sensitive comparison (default: False)
attribute: Item attribute to compare (default: None)
Returns:
Any: Minimum value
"""
def pprint(value, verbose=False):
"""
Pretty print value for debugging.
Parameters:
value: Input value
verbose: Include more detail (default: False)
Returns:
str: Pretty printed representation
"""
def reject(seq, func, *args, **kwargs):
"""
Reject items that pass test.
Parameters:
seq: Input sequence
func: Test name or callable
*args: Test arguments
**kwargs: Test keyword arguments
Returns:
Iterator: Items that failed test
"""
def rejectattr(seq, attribute, *args, **kwargs):
"""
Reject items by attribute test.
Parameters:
seq: Input sequence
attribute: Attribute name to test
*args: Test arguments
**kwargs: Test keyword arguments
Returns:
Iterator: Items that failed attribute test
"""
def select(seq, func, *args, **kwargs):
"""
Select items that pass test.
Parameters:
seq: Input sequence
func: Test name or callable
*args: Test arguments
**kwargs: Test keyword arguments
Returns:
Iterator: Items that passed test
"""
def selectattr(seq, attribute, *args, **kwargs):
"""
Select items by attribute test.
Parameters:
seq: Input sequence
attribute: Attribute name to test
*args: Test arguments
**kwargs: Test keyword arguments
Returns:
Iterator: Items that passed attribute test
"""
def tojson(value, indent=None):
"""
Convert value to JSON string.
Parameters:
value: Input value
indent: JSON indentation (default: None)
Returns:
str: JSON representation
"""
def xmlattr(d, autospace=True):
"""
Create XML attributes from dictionary.
Parameters:
d: Dictionary of attributes
autospace: Add leading space (default: True)
Returns:
Markup: XML attribute string
"""Filters can be chained together for complex data processing:
# Template usage
{{ user.name | lower | replace(' ', '_') | truncate(20) }}
# Programmatic usage
env = Environment()
result = env.call_filter('truncate',
env.call_filter('replace',
env.call_filter('lower', 'John Doe Smith'),
' ', '_'
),
20
)Add custom filters to environments:
def custom_format_filter(value, format_type='default'):
if format_type == 'upper':
return str(value).upper()
elif format_type == 'title':
return str(value).title()
return str(value)
env = Environment()
env.filters['custom_format'] = custom_format_filter
# Use in templates: {{ name | custom_format('title') }}class FilterEnvironment:
"""
Filter execution environment providing context and utilities for filter functions.
Attributes:
environment: Jinja2 environment instance
context: Current template context (if available)
eval_ctx: Current evaluation context (if available)
"""