# Filters Reference

URL: /kida/docs/reference/filters/
Section: reference
Description: All built-in filters with examples, including terminal color, style, layout, and data display filters

---

> For a complete page index, fetch /kida/llms.txt.

Complete reference for all built-in filters.

## String Filters

### abs

Return absolute value.

```kida
{{ -5 | abs }}  → 5
```

### capitalize

Capitalize first character.

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

### center

Center string in given width.

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

### escape / e

HTML-escape the value.

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

### format

Format string with arguments using Python `str.format()` and `{}` placeholders.

```kida
{{ "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 `decimal` or
> `format_number`:
>
> ```kida
> {{ price | decimal(2) }}           → 19.99
> {{ amount | format_number(2) }}    → 1,234.57
> ```

### indent

Indent text lines.

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

### lower

Convert to lowercase.

```kida
{{ "HELLO" | lower }}  → hello
```

### replace

Replace occurrences.

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

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

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

### safe

Mark a value as safe for the active render surface.

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

In HTML mode, this means trusted HTML. In Markdown mode, this means trusted Markdown and bypasses Markdown autoescape via the `__markdown__` protocol. Keep `safe` off untrusted issue, PR, tool, or user-provided text.

### striptags

Remove HTML tags.

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

### title

Title case.

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

### trim / strip

Remove whitespace.

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

### truncate

Truncate to length.

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

### upper

Convert to uppercase.

```kida
{{ "hello" | upper }}  → HELLO
```

### urlencode

URL-encode a string.

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

### date

Format datetime, date, or epoch timestamp with strftime.

```kida
{{ 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).

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

### wordcount

Count words.

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

### wordwrap

Wrap text at width.

```kida
{{ long_text | wordwrap(80) }}
```

---

## Collection Filters

### batch

Group items into batches.

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

### first

Return first item.

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

### groupby

Group by attribute.

```kida
{% 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.

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

`join` expects iterable input. Scalars like `42` now raise `TypeError` instead of falling back to
stringification.

### last

Return last item.

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

### length / count

Return item count.

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

### list

Convert to list.

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

### map

Extract attribute from items.

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

### max

Return maximum.

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

### min

Return minimum.

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

### reject

Reject items matching test.

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

### rejectattr

Reject items where attribute matches.

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

### reverse

Reverse an iterable or sequence.

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

`reverse` expects iterable input. If needed, coerce first:

```kida
{{ value | list | reverse }}
```

### select

Select items matching test.

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

### selectattr

Select items where attribute matches.

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

### skip

Skip first N items.

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

### slice

Slice into groups.

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

### sort

Sort sequence.

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

### sum

Sum values.

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

### take

Take first N items.

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

### unique

Remove duplicates.

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

### compact

Remove None/falsy values.

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

---

## Number Filters

### float

Convert to float.

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

### int

Convert to integer.

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

### round

Round number.

```kida
{{ 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.

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

### format_number / commas

Format with thousands separator.

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

Use `strict=true` to raise on invalid numeric conversion instead of returning the original value:

```kida
{{ 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.

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

Nested lists are flattened:

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

Conditional classes pattern:

```kida
<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.

```kida
{{ 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:

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

Use `strict=true` to raise on invalid numeric conversion:

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

---

## Utility Filters

### attr

Get attribute from object.

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

### default / d

Return default if undefined or None.

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

### pluralize

Django-style pluralization suffix.

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

`pluralize` expects numeric input. For YAML/config values, use `| int` first when needed.

### dictsort

Sort dict and return pairs.

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

### get

Safe dictionary/object access.

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

### pprint

Pretty-print value.

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

### require

Require non-None value.

```kida
{{ 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">`):

```kida
<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** (use `attr=true` so quotes do not break the attribute):

```kida
<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.

```kida
{{ 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.

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

---

## Debug Filters

### debug

Print debug info to stderr.

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

---

## Randomization Filters

**Warning**: These are impure (non-deterministic).

### random

Return random item.

```kida
{{ items | random }}
```

### shuffle

Return shuffled copy.

```kida
{{ items | shuffle }}
```

---

## Terminal Filters

Terminal filters are available when using `Environment(autoescape="terminal")` or `terminal_env()`. They produce `Styled` strings 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`.

```kida
{{ "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).

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

#### bg

Set background color. Same argument formats as `fg`.

```kida
{{ "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 |

```kida
{{ "Important" | bold }}
{{ "Secondary" | dim }}
{{ "Title" | underline }}
{{ title | bold | fg("cyan") }}
```

### Layout

#### pad

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

```kida
{{ 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.

```kida
{{ 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.

```kida
{{ 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`.

```kida
{{ "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.

```kida
{{ 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.

```kida
{{ "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.

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

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

## See Also

- [[docs/syntax/filters|Filter Syntax]] — Using filters
- [[docs/extending/custom-filters|Custom Filters]] — Create filters
- [[docs/usage/terminal-rendering|Terminal Rendering]] — Full terminal mode guide
