Skip to content

environment (4)

evaluate

evaluate(self, code: str, context: dict[str, typing.Any] | None = None) -> str

Evaluate python code and return the caught stdout + return value of last line.

Example

Jinja call:

{{ "1 + 2" | evaluate }}
Result: 3

DocStrings

Parameters:

Name Type Description Default
code str

The code to execute

required
context dict[str, Any] | None

Globals for the execution environment

None

Returns:

Type Description
str

The combined standard output and return value of the last

str

line of code.

Source code in src/jinjarope/environment.py
def evaluate(
    self,
    code: str,
    context: dict[str, Any] | None = None,
) -> str:
    """Evaluate python code and return the caught stdout + return value of last line.

    This function executes Python code within the environment's
    globals. It captures the standard output generated during
    execution and returns the combined result as a string.

    Args:
        code: The code to execute
        context: Globals for the execution environment

    Returns:
        The combined standard output and return value of the last
        line of code.
    """
    now = time.time()
    logger.debug("Evaluating code:\n%s", code)
    tree = ast.parse(code)
    eval_expr = ast.Expression(tree.body[-1].value)  # ty: ignore[missing-attribute]
    # exec_expr = ast.Module(tree.body[:-1])
    exec_expr = ast.parse("")
    exec_expr.body = tree.body[:-1]
    compiled = compile(exec_expr, "file", "exec")
    buffer = io.StringIO()
    with contextlib.redirect_stdout(buffer):
        exec(compiled, self.globals)
        val = eval(compile(eval_expr, "file", "eval"), self.globals)
    logger.debug("Code evaluation took %s seconds.", time.time() - now)
    # result = mk.MkContainer([buffer.getvalue(), val])
    return val or ""

render_file

render_file(self, file: str | os.PathLike[str], variables: dict[str, typing.Any] | None = None, **kwargs: Any) -> str

Helper to directly render a template from filesystem.

Example

Jinja call:

{{ "https://raw.githubusercontent.com/phil65/jinjarope/main/tests/__init__.py" | render_file }}
Result: """Tests suite forjinjarope`."""

from pathlib import Path

TESTS_DIR = Path(file).parent TMP_DIR = TESTS_DIR / "tmp" FIXTURES_DIR = TESTS_DIR / "fixtures"`

DocStrings

Parameters:

Name Type Description Default
file str | PathLike[str]

Template file to load

required
variables dict[str, Any] | None

Extra variables for the rendering

None
kwargs Any

Further extra variables for rendering

{}

Returns:

Type Description
str

The rendered string.

Source code in src/jinjarope/environment.py
def render_file(
    self,
    file: str | os.PathLike[str],
    variables: dict[str, Any] | None = None,
    **kwargs: Any,
) -> str:
    """Helper to directly render a template from filesystem.

    This function renders a template file directly from the
    filesystem using the current environment's configuration and
    globals.

    !!! info
        The file content is cached, which is generally acceptable
        for common use cases.

    Args:
        file: Template file to load
        variables: Extra variables for the rendering
        kwargs: Further extra variables for rendering

    Returns:
        The rendered string.
    """
    content = envglobals.load_file_cached(str(file))
    return self.render_string(content, variables, **kwargs)

render_string

render_string(self, string: str, variables: dict[str, typing.Any] | None = None, **kwargs: Any) -> str

Render a template string.

Example

Jinja call:

{{ "{{ a + 2 }} = 3" | render_string(a=1) }}
Result: 3 = 3

DocStrings

Parameters:

Name Type Description Default
string str

String to render

required
variables dict[str, Any] | None

Extra variables for the rendering

None
kwargs Any

Further extra variables for rendering

{}

Returns:

Type Description
str

The rendered string.

Source code in src/jinjarope/environment.py
def render_string(
    self,
    string: str,
    variables: dict[str, Any] | None = None,
    **kwargs: Any,
) -> str:
    """Render a template string.

    This function renders the given template string using the
    current environment's configuration and globals.

    Args:
        string: String to render
        variables: Extra variables for the rendering
        kwargs: Further extra variables for rendering

    Returns:
        The rendered string.
    """
    variables = (variables or {}) | kwargs
    cls = self.template_class
    try:
        template = cls.from_code(self, self.compile(string), self.globals, None)
    except TemplateSyntaxError as e:
        msg = f"Error when evaluating \n{string}\n (extra globals: {variables})"
        raise SyntaxError(msg) from e
    try:
        return template.render(**variables)
    except Exception as e:
        msg = f"Error when rendering \n{string}\n (extra globals: {variables})"
        raise RuntimeError(msg) from e

render_template

render_template(self, template_name: str, variables: dict[str, typing.Any] | None = None, block_name: str | None = None, parent_template: str | None = None, **kwargs: Any) -> str

Render a loaded template (or a block of a template).

Example

Jinja call:

{{ "docs/.empty" | render_template }}
Result:

DocStrings

Parameters:

Name Type Description Default
template_name str

Template name

required
variables dict[str, Any] | None

Extra variables for rendering

None
block_name str | None

Render specific block from the template

None
parent_template str | None

The name of the parent template importing this template

None
kwargs Any

Further extra variables for rendering

{}

Returns:

Type Description
str

The rendered string.

Raises:

Type Description
BlockNotFoundError

If the specified block is not found in the

Source code in src/jinjarope/environment.py
def render_template(
    self,
    template_name: str,
    variables: dict[str, Any] | None = None,
    block_name: str | None = None,
    parent_template: str | None = None,
    **kwargs: Any,
) -> str:
    """Render a loaded template (or a block of a template).

    This function renders a loaded template or a specific block from
    a template. It allows for the inclusion of parent templates and
    provides the flexibility to render individual blocks.

    Args:
        template_name: Template name
        variables: Extra variables for rendering
        block_name: Render specific block from the template
        parent_template: The name of the parent template importing this template
        kwargs: Further extra variables for rendering

    Returns:
        The rendered string.

    Raises:
        BlockNotFoundError: If the specified block is not found in the
        template.
    """
    variables = (variables or {}) | kwargs
    template = self.get_template(template_name, parent=parent_template)
    if not block_name:
        return template.render(**variables)
    try:
        block_render_func = template.blocks[block_name]
    except KeyError:
        raise BlockNotFoundError(block_name, template_name) from KeyError

    ctx = template.new_context(variables)
    return self.concat(block_render_func(ctx))