Skip to content

templates

Render exported ChatKit widget files with Jinja.

WidgetTemplate

Load and render a .widget definition into a canonical widget tree.

Source code in chatkit/templates.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class WidgetTemplate:
    """Load and render a `.widget` definition into a canonical widget tree."""

    def __init__(self, definition: dict[str, Any]):
        self.version = definition["version"]
        if self.version != "1.0":
            raise ValueError(f"Unsupported widget spec version: {self.version}")

        self.name = definition["name"]
        template = definition["template"]
        self.template = (
            template
            if isinstance(template, Template)
            else _jinja_env.from_string(template)
        )

    @classmethod
    def from_file(cls, path: str | Path) -> WidgetTemplate:
        """Read a widget definition. Relative paths use the working directory."""
        return cls(json.loads(Path(path).read_text(encoding="utf-8")))

    def build(
        self, data: dict[str, Any] | BaseModel | None = None
    ) -> widget_models.WidgetRoot:
        """Render template data into a Card, ListView, or Basic widget tree."""
        context = data.model_dump() if isinstance(data, BaseModel) else data
        return widget_models.WidgetRoot.model_validate_json(
            self.template.render(**(context or {}))
        )

from_file classmethod

from_file(path: str | Path) -> WidgetTemplate

Read a widget definition. Relative paths use the working directory.

Source code in chatkit/templates.py
31
32
33
34
@classmethod
def from_file(cls, path: str | Path) -> WidgetTemplate:
    """Read a widget definition. Relative paths use the working directory."""
    return cls(json.loads(Path(path).read_text(encoding="utf-8")))

build

build(data: dict[str, Any] | BaseModel | None = None) -> WidgetRoot

Render template data into a Card, ListView, or Basic widget tree.

Source code in chatkit/templates.py
36
37
38
39
40
41
42
43
def build(
    self, data: dict[str, Any] | BaseModel | None = None
) -> widget_models.WidgetRoot:
    """Render template data into a Card, ListView, or Basic widget tree."""
    context = data.model_dump() if isinstance(data, BaseModel) else data
    return widget_models.WidgetRoot.model_validate_json(
        self.template.render(**(context or {}))
    )