Skip to content

render_jinja_template

kedro_dagster.utils.render_jinja_template(src, is_cookiecutter=False, **kwargs)

Render a Jinja template from a file or string.

Parameters

Name Type Description Default
src str or Path

Path to the template file or template string.

required
is_cookiecutter bool

Whether to use cookiecutter-style rendering.

False
**kwargs Any

Variables to pass to the template.

{}

Returns

Type Description
str

Rendered template as a string.

See Also

kedro_dagster.utils.write_jinja_template : Renders and writes a template to disk in one step.

Source Code

Show/Hide source
def render_jinja_template(src: str | Path, is_cookiecutter: bool = False, **kwargs: Any) -> str:
    """Render a Jinja template from a file or string.

    Parameters
    ----------
    src : str or Path
        Path to the template file or template string.
    is_cookiecutter : bool, optional
        Whether to use cookiecutter-style rendering.
    **kwargs
        Variables to pass to the template.

    Returns
    -------
    str
        Rendered template as a string.

    See Also
    --------
    `kedro_dagster.utils.write_jinja_template` :
        Renders and writes a template to disk in one step.
    """
    # Resolve to an absolute filesystem path to avoid platform-specific quirks
    # with drive-less absolute paths on Windows (e.g., "/tmp").
    src = Path(src).resolve()

    template_loader = FileSystemLoader(searchpath=str(src.parent))
    # the keep_trailing_new_line option is mandatory to
    # make sure that black formatting will be preserved
    template_env = Environment(loader=template_loader, keep_trailing_newline=True)
    template = template_env.get_template(src.name)
    if is_cookiecutter:
        # we need to match tags from a cookiecutter object
        # but cookiecutter only deals with folder, not file
        # thus we need to create an object with all necessary attributes
        class FalseCookieCutter:
            def __init__(self, **kwargs: Any):
                self.__dict__.update(kwargs)

        parsed_template = template.render(cookiecutter=FalseCookieCutter(**kwargs))
    else:
        parsed_template = template.render(**kwargs)

    return parsed_template  # type: ignore[no-any-return]