Filter

Liquid filters are implemented as callables. They can be functions or classes with a __call__ method.

type liquid.Filter = Callable[[Concatenate[FilterContext, object, ...]], object]

The first argument passed to the callable is always an instance of FilterContext. It has useful methods for coercing arguments to acceptable types and raising exceptions.

The second argument is the result of evaluating the filter’s left value. That’s everything to the left of the filter operator (|). Conventionally we give the second argument the name left and the type object.

Remaining arguments are defined by the filter.

For example, this is the complete implementation of the built-in append filter.

from liquid import FilterContext

def append(context: FilterContext, left: object, right: object) -> str:
    return context.to_str(left, "") + context.to_str(right, "")

See built-in filters for many more examples.

API

class liquid.FilterContext(context: RenderContext, span: Token)

Liquid config, state and utilities for filter implementations.

error(message: str) → LiquidFilterError

Return a Liquid exception with suitable error context data.

get_item(obj: object, key: object, default: object = <liquid._nothing.Nothing object>) → object

Get key from obj with Shopify/liquid semantics.

input_array(obj: object) → list[object]

Coerce obj to a list suitable for filters that expect an array input.

is_nil(obj: object) → bool

Return true if obj is Liquid nullish.

to_date(obj: object) → dt.datetime | None

Coerce obj to a datatime, or None if obj can not be interpreted as a datetime.

to_int(obj: object) → int

Coerce obj to an integer.

to_numeric(obj: object, default: int | Decimal) → float | int | Decimal

Coerce obj to an integer, float or Decimal.

to_str(obj: object, default: T) → str | T

Coerce obj to a string.

truthy(obj: object) → bool

Return true if obj is Liquid truthy.