Filters Reference

All built-in filters with examples, including terminal color, style, layout, and data display filters

12 min read 2356 words

Complete reference for all built-in filters.

String Filters

abs

Return absolute value.

{{ -5 | abs }}  → 5

capitalize

Capitalize first character.

{{ "hello world" | capitalize }}  → Hello world

center

Center string in given width.

{{ "hi" | center(10) }}  → "    hi    "

escape / e

HTML-escape the value.

{{ "<script>" | escape }}  → &lt;script&gt;
{{ "<b>" | e }}  → &lt;b&gt;

format

Format string with arguments using Pythonstr.format() and {}placeholders.

{{ "Hello, {}!" | format(name) }}
{{ "{} + {} = {}" | format(1, 2, 3) }}
{{ "{:.2f}" | format(price) }}

%-style format strings are not supported. Using "%.2f" | format(x)raises a ValueError with a helpful message. For numeric formatting, prefer decimalor format_number:

er.

```kida
{{ "hello world" | capitalize }}  → Hello world
```

### cent

indent

Indent text lines.

{{ text | indent(4) }}
{{ text | indent(4, first=true) }}

lower

Convert to lowercase.

{{ "HELLO" | lower }}  → hello

replace

Replace occurrences.

{{ "hello" | replace("l", "L") }}  → heLLo
{{ "aaa" | replace("a", "b", 2) }}  → bba

countmay come from YAML/config as a string if it can be coerced to an integer:

{{ "hello" | replace("l", "L", "1") }}  → heLlo

safe

Mark as safe HTML (no escaping).

{{ html_content | safe }}
{{ trusted | safe(reason="sanitized") }}

striptags

Remove HTML tags.

{{ "<p>Hello</p>" | striptags }}  → Hello

title

Title case.

{{ "hello world" | title }}  → Hello World

trim / strip

Remove whitespace.

{{ "  hello  " | trim }}  → hello
{{ "xxhelloxx" | trim("x") }}  → hello

truncate

Truncate to length.

{{ text | truncate(50) }}
{{ text | truncate(50, killwords=true) }}
{{ text | truncate(50, end="[...]") }}

upper

Convert to uppercase.

{{ "hello" | upper }}  → HELLO

urlencode

URL-encode a string.

{{ "hello world" | urlencode }}  → hello%20world

date

Format datetime, date, or epoch timestamp with strftime.

{{ dt | date }}  → 2025-02-13
{{ dt | date("%b %d, %Y") }}  → Feb 13, 2025
{{ none | date }}  → ""
{{ 1707782400 | date }}  → epoch to date

slug

Convert text to URL-safe slug (lowercase, hyphens, ASCII-only).

{{ "Hello World" | slug }}  → hello-world
{{ "  foo  bar  " | slug }}  → foo-bar
{{ none | slug }}  → ""

wordcount

Count words.

{{ "hello world" | wordcount }}  → 2

wordwrap

Wrap text at width.

{{ long_text | wordwrap(80) }}

Collection Filters

batch

Group items into batches.

{% for row in items | batch(3) %}
    {% for item in row %}{{ item }}{% end %}
{% end %}

first

Return first item.

{{ items | first }}
{{ [1, 2, 3] | first }}  → 1

groupby

Group by attribute.

{% for group in posts | groupby("category") %}
    <h2>{{ group.grouper }}</h2>
    {% for post in group.list %}
        {{ post.title }}
    {% end %}
{% end %}

join

Join an iterable with a separator.

{{ items | join(", ") }}
{{ [1, 2, 3] | join("-") }}  → 1-2-3

join expects iterable input. Scalars like 42 now raise TypeErrorinstead of falling back to stringification.

last

Return last item.

{{ items | last }}
{{ [1, 2, 3] | last }}  → 3

length / count

Return item count.

{{ items | length }}
{{ "hello" | length }}  → 5

list

Convert to list.

{{ range(5) | list }}  → [0, 1, 2, 3, 4]

map

Extract attribute from items.

{{ users | map(attribute="name") | join(", ") }}

max

Return maximum.

{{ [1, 5, 3] | max }}  → 5
{{ items | max(attribute="score") }}

min

Return minimum.

{{ [1, 5, 3] | min }}  → 1
{{ items | min(attribute="price") }}

reject

Reject items matching test.

{{ items | reject("none") | list }}

rejectattr

Reject items where attribute matches.

{{ posts | rejectattr("is_draft") | list }}
{{ users | rejectattr("age", "lt", 18) | list }}

reverse

Reverse an iterable or sequence.

{{ [1, 2, 3] | reverse | list }}  → [3, 2, 1]

reverseexpects iterable input. If needed, coerce first:

{{ value | list | reverse }}

select

Select items matching test.

{{ items | select("defined") | list }}

selectattr

Select items where attribute matches.

{{ posts | selectattr("is_published") | list }}
{{ users | selectattr("role", "eq", "admin") | list }}

skip

Skip first N items.

{{ items | skip(5) }}
{{ posts | skip(10) | take(10) }}

slice

Slice into groups.

{% for column in items | slice(3) %}
    <div class="column">
        {% for item in column %}{{ item }}{% end %}
    </div>
{% end %}

sort

Sort sequence.

{{ items | sort }}
{{ items | sort(reverse=true) }}
{{ posts | sort(attribute="date") }}
{{ pages | sort(attribute="weight,title") }}

sum

Sum values.

{{ [1, 2, 3] | sum }}  → 6
{{ items | sum(attribute="price") }}

take

Take first N items.

{{ items | take(5) }}
{{ posts | sort(attribute="date", reverse=true) | take(3) }}

unique

Remove duplicates.

{{ items | unique }}
{{ posts | unique(attribute="category") }}

compact

Remove None/falsy values.

{{ [1, None, 2, "", 3] | compact }}  → [1, 2, 3]
{{ items | compact(truthy=false) }}  {# Only remove None #}

Number Filters

float

Convert to float.

{{ "3.14" | float }}  → 3.14
{{ "bad" | float(default=0.0) }}  → 0.0

int

Convert to integer.

{{ "42" | int }}  → 42
{{ "bad" | int(default=0) }}  → 0

round

Round number.

{{ 3.7 | round }}  → 4
{{ 3.14159 | round(2) }}  → 3.14
{{ 3.5 | round(method="ceil") }}  → 4
{{ 3.5 | round(method="floor") }}  → 3

filesizeformat

Format bytes as human-readable.

{{ 1024 | filesizeformat }}  → 1.0 kB
{{ 1048576 | filesizeformat(binary=true) }}  → 1.0 MiB

format_number / commas

Format with thousands separator.

{{ 1234567 | format_number }}  → 1,234,567
{{ 1234.5 | format_number(2) }}  → 1,234.50
{{ 1000000 | commas }}  → 1,000,000

Use strict=trueto raise on invalid numeric conversion instead of returning the original value:

{{ price | format_number(2, strict=true) }}

CSS / HTML Filters

classes

Join a list of CSS class names, dropping falsy values. Useful for conditional class composition.

{{ ["btn", "btn-primary", ""] | classes }}  → btn btn-primary
{{ ["card", none, "shadow"] | classes }}  → card shadow

Nested lists are flattened:

{{ ["base", ["active", ""], "highlight"] | classes }}  → base active highlight

Conditional classes pattern:

<div class="{{ ["card", "active" if is_active, "disabled" if is_disabled] | classes }}">

Number Filters

decimal

Format a number to a fixed number of decimal places.

{{ 3.14159 | decimal(2) }}  → 3.14
{{ 42 | decimal(2) }}  → 42.00
{{ 1.5 | decimal(0) }}  → 2
{{ 0.1 + 0.2 | decimal(1) }}  → 0.3

Non-numeric values pass through unchanged:

{{ "hello" | decimal(2) }}  → hello

Use strict=trueto raise on invalid numeric conversion:

{{ value | decimal(2, strict=true) }}

Utility Filters

attr

Get attribute from object.

{{ user | attr("name") }}

default / d

Return default if undefined or None.

{{ missing | default("N/A") }}
{{ value | d("fallback") }}
{{ maybe_false | default(true, boolean=true) }}

pluralize

Django-style pluralization suffix.

{{ 1 | pluralize }}  → ""
{{ 2 | pluralize }}  → s
{{ 1 | pluralize("y,ies") }}  → y
{{ 2 | pluralize("y,ies") }}  → ies

pluralize expects numeric input. For YAML/config values, use | intfirst when needed.

dictsort

Sort dict and return pairs.

{% for key, value in data | dictsort %}
    {{ key }}: {{ value }}
{% end %}

get

Safe dictionary/object access.

{{ config | get("timeout", 30) }}
{{ data | get("items") }}  {# Avoids method name conflict #}

pprint

Pretty-print value.

<pre>{{ data | pprint }}</pre>

require

Require non-None value.

{{ user.id | require("User ID required") }}

tojson

Convert a value to a JSON string (marked safe so the autoescaper does not double-escape).

Parameter Type Default Description
indent int | None None JSON indentation level
attr bool False HTML-entity-encode for safe use in double-quoted HTML attributes

In<script> tags (default — raw JSON; fine for trusted data and <script type="application/json">):

<script type="application/json">{{ data | tojson }}</script>
<script>const data = {{ config | tojson }};</script>
{{ data | tojson(indent=2) }}

Raw tojson output does not escape </script> or < inside the JSON text. If the serialized data is not trusted, avoid inlining it in an executable <script> block; use type="application/json"and parse in JS, or fetch JSON separately.

In HTML attributes (useattr=trueso quotes do not break the attribute):

<div x-data="{{ config | tojson(attr=true) }}">

You can also use a single-quoted attribute with the default filter: x-data='{{ config | tojson }}'.

typeof

Return a normalized type name for debugging template data.

{{ value | typeof }}  → str
{{ none | typeof }}  → none
{{ some_path | typeof }}  → path

Common normalized names include bool, int, float, path, list, dict, none, and str.

xmlattr

Convert dict to XML attributes.

<div{{ attrs | xmlattr }}></div>

Debug Filters

debug

Print debug info to stderr.

{{ posts | debug }}
{{ posts | debug("my posts") }}
{{ items | debug(max_items=10) }}

Randomization Filters

Warning: These are impure (non-deterministic).

random

Return random item.

{{ items | random }}

shuffle

Return shuffled copy.

{{ items | shuffle }}

Terminal Filters

Terminal filters are available when usingEnvironment(autoescape="terminal") or terminal_env(). They produce Styledstrings with ANSI escape sequences and degrade gracefully when color or Unicode is unavailable.

Color & Style

Named Colors

Apply a foreground color directly by name. Available colors:black, red, green, yellow, blue, magenta, cyan, white, bright_red, bright_green, bright_yellow, bright_blue, bright_magenta, bright_cyan.

{{ "Error" | red }}
{{ "OK" | green }}
{{ "Note" | bright_cyan }}

fg

Set foreground color by name, hex, 256-color index, or RGB tuple. Degrades across color depths (truecolor -> 256 -> basic -> none).

{{ "Hello" | fg("red") }}
{{ "Hello" | fg("#ff5733") }}
{{ "Hello" | fg(196) }}

bg

Set background color. Same argument formats asfg.

{{ "Alert" | bg("yellow") }}
{{ "Highlight" | bg("#333333") }}

Decoration Filters

Apply text decoration. Each degrades to plain text when color is disabled.

Filter Effect
bold Bold / bright
dim Dimmed / faint
italic Italic
underline Underlined
strike Strikethrough
blink Blinking (terminal support varies)
inverse Swap foreground and background
{{ "Important" | bold }}
{{ "Secondary" | dim }}
{{ "Title" | underline }}
{{ title | bold | fg("cyan") }}

Layout

pad

Pad a value to a fixed visible width, respecting ANSI escape sequences.

{{ name | pad(30) }}
{{ name | pad(30, align="right") }}
{{ name | pad(30, align="center", fill=".") }}

Parameters: width (int), align ("left", "right", "center"), fill(str, default " ").

table

Render a list of dicts (or list of lists) as a bordered table.

{{ users | table }}
{{ users | table(headers=["Name", "Role"], border="heavy") }}
{{ users | table(align={"score": "right"}, max_width=80) }}

Parameters: headers (list, optional), border ("light", "heavy", "double", "ascii"), align (dict mapping column name to "left"/"right"/"center"), max_width(int, optional).

tree

Render a nested dict as an indented tree with box-drawing connectors.

{{ file_tree | tree }}
{{ file_tree | tree(indent=4) }}

Parameters: indent(int, default 2).

Output:

├── src
│   ├── main.py
│   └── utils.py
└── tests
    └── test_main.py

Data Display

badge

Render a status value as a colored icon badge. Recognizes common statuses:pass, success, ok, fail, error, warn, warning, skip, info.

{{ "pass" | badge }}
{{ "fail" | badge }}
{{ "Custom" | badge(icon="info", badge_color="blue") }}

Parameters: icon (str, optional — icon name or literal character), badge_color(str, optional — named color).

bar

Render a progress bar from a 0.0–1.0 value.

{{ 0.75 | bar }}
{{ 0.75 | bar(width=30, show_pct=false) }}

Parameters: width (int, default 20), show_pct(bool, default true).

Output:████████████████░░░░ 75%

kv

Render a key-value pair with dot-fill alignment.

{{ "Status" | kv("Running") }}
{{ "CPU" | kv("42%", width=50) }}

Parameters: value (any), width (int, default 40), sep (str, default " "), fill(str, default "·").

Output:Status ······················· Running

diff

Render a unified diff between two strings with color-coded additions and removals.

{{ old_config | diff(new_config) }}
{{ old_config | diff(new_config, context=5) }}

Parameters: new (any), context(int, default 3).

See Also