> ## Documentation Index
> Fetch the complete documentation index at: https://puzzlet-9ba7bb98.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Filters

> Transform and format template values with built-in TemplateDX filter functions.

Filters are functions that take an input value and return a transformed output. TemplateDX ships ten built-in filters and exposes two ways to register your own: a global static API and a per-instance API on `TemplateDX`.

## Creating custom filters (TypeScript)

### `FilterRegistry.register` (static or instance API)

**Static (global) registration** is the simplest path; everything using the default `transform`/`stringify` exports sees it:

```typescript theme={null}
import { FilterRegistry } from '@agentmark-ai/templatedx';

FilterRegistry.register(name, filterFunction);
```

**Parameters**

* `name` (string): The name used to call the filter in templates.
* `filterFunction` (FilterFunction): The function that performs the transformation.

**Instance (scoped) registration** is for when you want filters isolated per engine:

```typescript theme={null}
import { TemplateDX } from '@agentmark-ai/templatedx';

const engine = new TemplateDX({ includeBuiltins: true });
engine.registerFilter(name, filterFunction);

const rendered = await engine.transform(ast, { /* props */ });
```

`new TemplateDX({ includeBuiltins: true })` copies the built-in filters into the instance; pass `false` to start empty.

### `FilterFunction` type

The `FilterFunction` type signature is:

```typescript theme={null}
type FilterFunction<
  Input = any,
  Output = any,
  Args extends any[] = any[]
> = (input: Input, ...args: Args) => Output;
```

* `input` - The first argument is always the value the filter receives.
* `...args` - Additional arguments passed to the filter.

### Example: custom filter

Here's an example of creating a custom `reverse` filter that reverses a string:

```typescript theme={null}
import { FilterRegistry, FilterFunction } from '@agentmark-ai/templatedx';

const reverse: FilterFunction<string, string> = (input) => {
  if (typeof input !== 'string') return input;
  return input.split('').reverse().join('');
};

FilterRegistry.register('reverse', reverse);
```

Usage:

```tsx theme={null}
{reverse("hello")}
```

**Output**

```text theme={null}
olleh
```

### Example: filter with arguments

Filters can accept additional arguments. Here's a `pad` filter that pads a string to a specified length:

```typescript theme={null}
import { FilterRegistry, FilterFunction } from '@agentmark-ai/templatedx';

const pad: FilterFunction<string, string, [number, string?]> = (
  input,
  length,
  char = ' '
) => {
  if (typeof input !== 'string') return input;
  return input.padStart(length, char);
};

FilterRegistry.register('pad', pad);
```

Usage:

```tsx theme={null}
{pad("42", 5, "0")}
```

**Output**

```text theme={null}
00042
```

## Creating custom filters (Python)

`agentmark-templatedx` (Python) mirrors the TS surface. Define a function and register it via the static (`register_global`) or instance API:

```python theme={null}
from templatedx import FilterRegistry

def reverse(value):
    if not isinstance(value, str):
        return value
    return value[::-1]

# Global (static) registration
FilterRegistry.register_global("reverse", reverse)
```

Unlike the tag registry (which takes the plugin first), filter registration takes the name first in both languages: `register_global(name, func)`.

For instance-scoped registration, construct the engine and use `register_filter`:

```python theme={null}
from templatedx import TemplateDX

engine = TemplateDX()  # always copies global built-ins on init
engine.register_filter("reverse", reverse)

result = await engine.transform(ast, {"name": "Alice"})
```

## Built-in filters

### `abs`

The `abs` filter returns the absolute value of a number.

**Syntax**

```tsx theme={null}
abs(number_value)
```

**Parameters**

* `number_value` (number): The input number.

**Example**

```tsx theme={null}
abs(-42)
```

**Output**

```text theme={null}
42
```

### `capitalize`

The `capitalize` filter capitalizes the first character of a string.

**Syntax**

```tsx theme={null}
capitalize(string_value)
```

**Parameters**

* `string_value` (string): The input string to capitalize.

**Example**

```tsx theme={null}
capitalize("hello world")
```

**Output**

```text theme={null}
Hello world
```

### `dump`

The `dump` filter serializes a JavaScript object into a JSON string.

**Syntax**

```tsx theme={null}
dump(object_value)
```

**Parameters**

* `object_value` (any): The input object to serialize.

**Example**

```tsx theme={null}
dump({ name: "TemplateDX", version: "1.0" })
```

**Output**

```text theme={null}
\{"name":"TemplateDX","version":"1.0"}
```

The leading backslash comes from the final `stringify` step, which escapes `{` at the start of text output. This applies to any filter output that begins with `{` or `[`.

### `join`

The `join` filter joins elements of an array into a single string, separated by a specified separator.

**Syntax**

```tsx theme={null}
join(array_value, separator)
```

**Parameters**

* `array_value` (any\[]): The input array.
* `separator` (string, optional): The string to separate the array elements. Defaults to `", "`.

**Example**

```tsx theme={null}
join(["apple", "banana", "cherry"], ", ")
```

**Output**

```text theme={null}
apple, banana, cherry
```

### `lower`

The `lower` filter converts a string to lowercase letters.

**Syntax**

```tsx theme={null}
lower(string_value)
```

**Parameters**

* `string_value` (string): The input string to convert to lowercase.

**Example**

```tsx theme={null}
lower("HELLO WORLD")
```

**Output**

```text theme={null}
hello world
```

### `replace`

The `replace` filter replaces all occurrences of a specified substring with a new substring.

**Syntax**

```tsx theme={null}
replace(string_value, search, replace)
```

**Parameters**

* `string_value` (string): The input string.
* `search` (string): The substring to search for.
* `replace` (string): The substring to replace with.

**Example**

```tsx theme={null}
replace("Hello World", "World", "TemplateDX")
```

**Output**

```text theme={null}
Hello TemplateDX
```

### `round`

The `round` filter rounds a number to a specified number of decimal places.

**Syntax**

```tsx theme={null}
round(number_value, decimals)
```

**Parameters**

* `number_value` (number): The input number to round.
* `decimals` (number, optional): The number of decimal places to round to. Defaults to `0`.

**Example**

```tsx theme={null}
round(3.14159, 2)
```

**Output**

```text theme={null}
3.14
```

### `truncate`

The `truncate` filter truncates a string to a specified length and appends an ellipsis (`...`) if necessary.

**Syntax**

```tsx theme={null}
truncate(string_value, length)
```

**Parameters**

* `string_value` (string): The input string to truncate.
* `length` (number): The maximum length of the output string.

**Example**

```tsx theme={null}
truncate("The quick brown fox jumps over the lazy dog", 20)
```

**Output**

```text theme={null}
The quick brown fox ...
```

`truncate` takes the first `length` characters and appends `...`, so the output is `length + 3` characters total.

### `upper`

The `upper` filter converts a string to uppercase letters.

**Syntax**

```tsx theme={null}
upper(string_value)
```

**Parameters**

* `string_value` (string): The input string to convert to uppercase.

**Example**

```tsx theme={null}
upper("hello world")
```

**Output**

```text theme={null}
HELLO WORLD
```

### urlencode

The `urlencode` filter encodes a string to be safe for use in URLs.

**Syntax**

```tsx theme={null}
urlencode(string_value)
```

**Parameters**

* `string_value` (string): The input string to be URL-encoded.

**Example**

```tsx theme={null}
urlencode("Hello World!")
```

**Output**

```text theme={null}
Hello%20World!
```

`urlencode` uses `encodeURIComponent`, which leaves `! * ' ( )` unencoded by spec.

## Next steps

Filters transform values inside expressions; for control flow and custom block behavior, see [Tags](/templatedx/tags).
