Skip to content

loaders

Class info

Classes

Name Children Inherits
ChoiceLoader
jinjarope.loaders
A loader which combines multiple other loaders.
    DictLoader
    jinjarope.loaders
    A loader to load static content from a path->template-str mapping.
      FileSystemLoader
      jinjarope.loaders
      A loader to load templates from the file system.
        FunctionLoader
        jinjarope.loaders
        A loader for loading templates from a function.
          LoaderMixin
          jinjarope.loaders
          Loader mixin which allows to OR loaders into a choice loader.
          ModuleLoader
          jinjarope.loaders
          This loader loads templates from precompiled templates.
            PackageLoader
            jinjarope.loaders
            A loader for loading templates from a package.
              PrefixLoader
              jinjarope.loaders
              A loader for prefixing other loaders.

                🛈 DocStrings

                ChoiceLoader

                Bases: LoaderMixin, ChoiceLoader

                A loader which combines multiple other loaders.

                Source code in src/jinjarope/loaders.py
                186
                187
                188
                189
                190
                191
                192
                193
                194
                195
                196
                197
                198
                199
                200
                201
                202
                203
                204
                class ChoiceLoader(LoaderMixin, jinja2.ChoiceLoader):
                    """A loader which combines multiple other loaders."""
                
                    ID = "choice"
                
                    def __repr__(self):
                        return utils.get_repr(self, loaders=self.loaders)
                
                    def __bool__(self):
                        return len(self.loaders) > 0
                
                    def __eq__(self, other):
                        return type(self) is type(other) and self.loaders == other.loaders
                
                    def __hash__(self):
                        return hash(tuple(self.loaders))
                
                    def __iter__(self):
                        return iter(self.loaders)
                

                DictLoader

                Bases: LoaderMixin, DictLoader

                A loader to load static content from a path->template-str mapping.

                Source code in src/jinjarope/loaders.py
                207
                208
                209
                210
                211
                212
                213
                214
                215
                216
                217
                218
                219
                220
                221
                222
                223
                224
                225
                226
                class DictLoader(LoaderMixin, jinja2.DictLoader):
                    """A loader to load static content from a path->template-str mapping."""
                
                    ID = "dict"
                
                    def __repr__(self):
                        return utils.get_repr(self, mapping=self.mapping)
                
                    def __add__(self, other: dict[str, str] | jinja2.DictLoader) -> DictLoader:
                        if isinstance(other, jinja2.DictLoader):
                            mapping = {**self.mapping, **other.mapping}
                        else:
                            mapping = {**self.mapping, **other}
                        return DictLoader(mapping)
                
                    def __eq__(self, other):
                        return type(self) is type(other) and self.mapping == other.mapping
                
                    def __hash__(self):
                        return hash(tuple(sorted(self.mapping.items())))
                

                FileSystemLoader

                Bases: LoaderMixin, FileSystemLoader

                A loader to load templates from the file system.

                Source code in src/jinjarope/loaders.py
                164
                165
                166
                167
                168
                169
                170
                171
                172
                173
                174
                175
                176
                177
                178
                179
                180
                181
                182
                183
                class FileSystemLoader(LoaderMixin, jinja2.FileSystemLoader):
                    """A loader to load templates from the file system."""
                
                    ID = "filesystem"
                
                    def __repr__(self):
                        return utils.get_repr(self, searchpath=self.searchpath)
                
                    def __add__(self, other) -> FileSystemLoader:
                        ls = [other] if isinstance(other, jinja2.FileSystemLoader) else other.serchpath
                        return FileSystemLoader([*self.searchpath, *ls])  # pyright: ignore
                
                    def __bool__(self):
                        return len(self.searchpath) > 0
                
                    def __eq__(self, other):
                        return type(self) is type(other) and self.searchpath == other.searchpath
                
                    def __hash__(self):
                        return hash(tuple(self.searchpath))
                

                FunctionLoader

                Bases: LoaderMixin, FunctionLoader

                A loader for loading templates from a function.

                The function takes a template path as parameter and either returns a (text, None, uptodate_fn) tuple or just the text as str.

                Source code in src/jinjarope/loaders.py
                 98
                 99
                100
                101
                102
                103
                104
                105
                106
                107
                108
                109
                110
                111
                112
                113
                114
                class FunctionLoader(LoaderMixin, jinja2.FunctionLoader):
                    """A loader for loading templates from a function.
                
                    The function takes a template path as parameter and either returns
                    a (text, None, uptodate_fn) tuple or just the text as str.
                    """
                
                    ID = "function"
                
                    def __repr__(self):
                        return utils.get_repr(self, self.load_func)
                
                    def __eq__(self, other):
                        return type(self) is type(other) and self.load_func == other.load_func
                
                    def __hash__(self):
                        return hash(self.load_func)
                

                LoaderMixin

                Loader mixin which allows to OR loaders into a choice loader.

                Source code in src/jinjarope/loaders.py
                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
                44
                45
                46
                47
                48
                49
                50
                51
                52
                class LoaderMixin:
                    """Loader mixin which allows to OR loaders into a choice loader."""
                
                    ID: str
                    loader: jinja2.BaseLoader
                    list_templates: Callable
                    get_source: Callable
                    load: Callable
                
                    def __or__(self, other: jinja2.BaseLoader) -> ChoiceLoader:
                        own = self.loaders if isinstance(self, jinja2.ChoiceLoader) else [self]  # type: ignore[list-item]
                        others = other.loaders if isinstance(other, jinja2.ChoiceLoader) else [other]
                        return ChoiceLoader([*own, *others])
                
                    def __getitem__(self, val: str) -> jinja2.Template:
                        """Return the template object for given template path."""
                        return self.load(None, val)
                
                    def __contains__(self, path: str):
                        """Check whether given path is loadable by this loader."""
                        return upath.UPath(path).as_posix() in self.list_templates()
                
                    def __rtruediv__(self, path: str):
                        return self.prefixed_with(path)
                
                    def prefixed_with(self, prefix: str):
                        """Return loader wrapped in a PrefixLoader instance with given prefix.
                
                        Args:
                            prefix: The prefix to use
                        """
                        return PrefixLoader({prefix: self})  # type: ignore[dict-item]
                
                    def get_template_source(self, template_path: str):
                        """Return the source for given template path."""
                        return self.get_source(None, template_path)[0]
                

                __contains__

                __contains__(path: str)
                

                Check whether given path is loadable by this loader.

                Source code in src/jinjarope/loaders.py
                35
                36
                37
                def __contains__(self, path: str):
                    """Check whether given path is loadable by this loader."""
                    return upath.UPath(path).as_posix() in self.list_templates()
                

                __getitem__

                __getitem__(val: str) -> Template
                

                Return the template object for given template path.

                Source code in src/jinjarope/loaders.py
                31
                32
                33
                def __getitem__(self, val: str) -> jinja2.Template:
                    """Return the template object for given template path."""
                    return self.load(None, val)
                

                get_template_source

                get_template_source(template_path: str)
                

                Return the source for given template path.

                Source code in src/jinjarope/loaders.py
                50
                51
                52
                def get_template_source(self, template_path: str):
                    """Return the source for given template path."""
                    return self.get_source(None, template_path)[0]
                

                prefixed_with

                prefixed_with(prefix: str)
                

                Return loader wrapped in a PrefixLoader instance with given prefix.

                Parameters:

                Name Type Description Default
                prefix str

                The prefix to use

                required
                Source code in src/jinjarope/loaders.py
                42
                43
                44
                45
                46
                47
                48
                def prefixed_with(self, prefix: str):
                    """Return loader wrapped in a PrefixLoader instance with given prefix.
                
                    Args:
                        prefix: The prefix to use
                    """
                    return PrefixLoader({prefix: self})  # type: ignore[dict-item]
                

                ModuleLoader

                Bases: LoaderMixin, ModuleLoader

                This loader loads templates from precompiled templates.

                Templates can be precompiled with :meth:Environment.compile_templates.

                Source code in src/jinjarope/loaders.py
                76
                77
                78
                79
                80
                81
                82
                83
                84
                85
                86
                87
                88
                89
                90
                91
                92
                93
                94
                95
                class ModuleLoader(LoaderMixin, jinja2.ModuleLoader):
                    """This loader loads templates from precompiled templates.
                
                    Templates can be precompiled with :meth:`Environment.compile_templates`.
                    """
                
                    ID = "module"
                
                    def __repr__(self):
                        return utils.get_repr(self, path=self.module.__path__)
                
                    def __eq__(self, other):
                        return (
                            type(self) is type(other)
                            and self.package_name == other.package_name
                            and self.module == other.module
                        )
                
                    def __hash__(self):
                        return hash(self.package_name) + hash(self.module)
                

                PackageLoader

                Bases: LoaderMixin, PackageLoader

                A loader for loading templates from a package.

                Source code in src/jinjarope/loaders.py
                117
                118
                119
                120
                121
                122
                123
                124
                125
                126
                127
                128
                129
                130
                131
                132
                133
                134
                135
                136
                137
                138
                139
                140
                141
                142
                143
                144
                145
                146
                147
                148
                149
                150
                151
                152
                153
                154
                155
                156
                157
                158
                159
                160
                161
                class PackageLoader(LoaderMixin, jinja2.PackageLoader):
                    """A loader for loading templates from a package."""
                
                    ID = "package"
                
                    def __init__(
                        self,
                        package: str | types.ModuleType,
                        package_path: str | None = None,
                        encoding: str = "utf-8",
                    ) -> None:
                        """Instanciate a PackageLoader.
                
                        Compared to the jinja2 equivalent, this loader also supports
                        `ModuleType`s and dotted module paths for the `package` argument.
                
                        Args:
                            package: The python package to create a loader for
                            package_path: If given, use the given path as the root.
                            encoding: The encoding to use for loading templates
                        """
                        if isinstance(package, types.ModuleType):
                            package = package.__name__
                        parts = package.split(".")
                        path = "/".join(parts[1:])
                        if package_path:
                            path = (pathlib.Path(path) / package_path).as_posix()
                        super().__init__(parts[0], path, encoding)
                
                    def __repr__(self):
                        return utils.get_repr(
                            self,
                            package_name=self.package_name,
                            package_path=self.package_path,
                        )
                
                    def __eq__(self, other):
                        return (
                            type(self) is type(other)
                            and self.package_name == other.package_name
                            and self.package_path == other.package_path
                        )
                
                    def __hash__(self):
                        return hash(self.package_name) + hash(self.package_path)
                

                __init__

                __init__(
                    package: str | ModuleType, package_path: str | None = None, encoding: str = "utf-8"
                ) -> None
                

                Instanciate a PackageLoader.

                Compared to the jinja2 equivalent, this loader also supports ModuleTypes and dotted module paths for the package argument.

                Parameters:

                Name Type Description Default
                package str | ModuleType

                The python package to create a loader for

                required
                package_path str | None

                If given, use the given path as the root.

                None
                encoding str

                The encoding to use for loading templates

                'utf-8'
                Source code in src/jinjarope/loaders.py
                122
                123
                124
                125
                126
                127
                128
                129
                130
                131
                132
                133
                134
                135
                136
                137
                138
                139
                140
                141
                142
                143
                144
                def __init__(
                    self,
                    package: str | types.ModuleType,
                    package_path: str | None = None,
                    encoding: str = "utf-8",
                ) -> None:
                    """Instanciate a PackageLoader.
                
                    Compared to the jinja2 equivalent, this loader also supports
                    `ModuleType`s and dotted module paths for the `package` argument.
                
                    Args:
                        package: The python package to create a loader for
                        package_path: If given, use the given path as the root.
                        encoding: The encoding to use for loading templates
                    """
                    if isinstance(package, types.ModuleType):
                        package = package.__name__
                    parts = package.split(".")
                    path = "/".join(parts[1:])
                    if package_path:
                        path = (pathlib.Path(path) / package_path).as_posix()
                    super().__init__(parts[0], path, encoding)
                

                PrefixLoader

                Bases: LoaderMixin, PrefixLoader

                A loader for prefixing other loaders.

                Source code in src/jinjarope/loaders.py
                55
                56
                57
                58
                59
                60
                61
                62
                63
                64
                65
                66
                67
                68
                69
                70
                71
                72
                73
                class PrefixLoader(LoaderMixin, jinja2.PrefixLoader):
                    """A loader for prefixing other loaders."""
                
                    ID = "prefix"
                
                    def __repr__(self):
                        return utils.get_repr(self, self.mapping)
                
                    def __eq__(self, other):
                        return type(self) is type(other) and self.mapping == other.mapping
                
                    def __hash__(self):
                        return hash(tuple(sorted(self.mapping.items())))
                
                    def __bool__(self):
                        return bool(self.mapping)
                
                    def __iter__(self):
                        return iter(self.mapping)
                

                from_json

                from_json(dct_or_list: dict | list | None | BaseLoader) -> BaseLoader | None
                

                Create a loader based on a json representation.

                Parameters:

                Name Type Description Default
                dct_or_list dict | list | None | BaseLoader

                A dictionary or list describing loaders.

                required
                Source code in src/jinjarope/loaders.py
                229
                230
                231
                232
                233
                234
                235
                236
                237
                238
                239
                240
                241
                242
                243
                244
                245
                246
                247
                248
                249
                250
                251
                252
                253
                254
                255
                256
                257
                258
                259
                260
                261
                262
                263
                264
                265
                266
                267
                268
                269
                270
                271
                272
                273
                274
                275
                276
                277
                278
                279
                def from_json(
                    dct_or_list: dict | list | None | jinja2.BaseLoader,
                ) -> jinja2.BaseLoader | None:
                    """Create a loader based on a json representation.
                
                    Args:
                        dct_or_list: A dictionary or list describing loaders.
                    """
                    from jinjarope import fsspecloaders
                
                    if not dct_or_list:
                        return None
                    loaders = []
                    ls = dct_or_list if isinstance(dct_or_list, list) else [dct_or_list]
                    for item in ls:
                        match item:
                            case jinja2.BaseLoader():
                                loader = item
                            case str() if "://" in item:
                                loader = fsspecloaders.FsSpecFileSystemLoader(item)
                            case str():
                                loader = FileSystemLoader(item)
                            case types.ModuleType():
                                loader = PackageLoader(item)
                            case dict():
                                dct_copy = item.copy()
                                typ = dct_copy.pop("type")
                                mapping = dct_copy.pop("mapping", None)
                                prefix = dct_copy.pop("prefix", None)
                                kls = next(
                                    kls
                                    for kls in inspectfilters.list_subclasses(jinja2.BaseLoader)
                                    if getattr(kls, "ID", None) == typ
                                )
                                if kls.ID == "prefix":  # type: ignore[attr-defined]
                                    mapping = {k: from_json(v) for k, v in mapping.items()}
                                    loader = kls(mapping)  # type: ignore[call-arg]
                                elif prefix:
                                    loader = prefix / kls(**dct_copy)
                                else:
                                    loader = kls(**dct_copy)
                            case _:
                                raise TypeError(item)
                        loaders.append(loader)
                    match len(loaders):
                        case 1:
                            return loaders[0]
                        case 0:
                            return None
                        case _:
                            return ChoiceLoader(loaders)