def _preload_templates()

in atr/preload.py [0:0]


def _preload_templates(app: base.QuartApp) -> None:
    """Preload all templates in the templates directory."""
    # We must disable automatic reload otherwise Jinja will check for modifications
    # Checking for modifications means that Jinja will call os.stat() in an asynchronous context
    app.jinja_env.auto_reload = False

    template_dir = pathlib.Path(os.path.join(os.path.dirname(os.getcwd()), "atr", "templates"))

    if not template_dir.exists():
        print(f"Warning: Template directory {template_dir} does not exist")
        return

    # Find all template files
    template_files: list[pathlib.Path] = []
    for extension in [".html", ".jinja", ".j2", ".txt"]:
        template_files.extend(template_dir.glob(f"**/*{extension}"))

    # For each template file, get its path relative to the template directory
    for template_file in template_files:
        try:
            relative_path = template_file.relative_to(template_dir)
            template_name = str(relative_path).replace("\\", "/")

            # Access the template to make Jinja load and cache it
            app.jinja_env.get_template(template_name)
        except Exception as e:
            print(f"Error preloading template {template_file}: {e}")
    print(f"Preloaded {len(template_files)} templates")