Skip to content

template

apply_template(content, ctx={})

Render content as a Jinja2 template with the provided context.

Parameters:

Name Type Description Default
content Any

Content to render as a template. Will be converted to string.

required
ctx dict[str, Any]

Dictionary of variables available in the template context. Defaults to empty dict.

{}

Returns:

Name Type Description
str str

The rendered template with variables substituted and whitespace normalized via dedent.

Example

apply_template("Hello {{ name }}!", {"name": "World"}) 'Hello World!'

Source code in agenty/template.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def apply_template(content: Any, ctx: dict[str, Any] = {}) -> str:
    """Render content as a Jinja2 template with the provided context.

    Args:
        content: Content to render as a template. Will be converted to string.
        ctx: Dictionary of variables available in the template context.
             Defaults to empty dict.

    Returns:
        str: The rendered template with variables substituted and whitespace
             normalized via dedent.

    Example:
        >>> apply_template("Hello {{ name }}!", {"name": "World"})
        'Hello World!'
    """
    return dedent(SandboxedEnvironment().from_string(str(content)).render(**ctx))