Skip to content

Custom Formatters

To create a custom formatter, you need to define a new class that inherits from BaseFormatter and implement the format method.

Below is an example of how to create a simple custom formatter, that replaces the cell content with a bold "Hello World" text.

from ckanext.tables.shared import BaseFormatter

class MyCustomFormatter(BaseFormatter):
    """Replaces cell content with a bold Hello World."""

    def format(
        self, value: types.Value, options: types.Options
    ) -> types.FormatterResult:
        return tk.literal(f"<strong>Hello World</strong>")

Each formatter has an access to the cell value and the options passed to the formatter. Also, self.table, self.row, and self.column attributes are available to access the table, row, and column definitions respectively.

BaseFormatter

Abstract base class for all formatters.

Source code in ckanext/tables/formatters.py
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class BaseFormatter(abc.ABC):
    """Abstract base class for all formatters."""

    def __init__(
        self,
        column: table.ColumnDefinition,
        row: types.Row,
        table: table.TableDefinition,
    ):
        self.column = column
        self.row = row
        self.table = table

    @abc.abstractmethod
    def format(self, value: types.Value, options: types.Options) -> types.FormatterResult:
        raise NotImplementedError