Skip to content

configloaders

Class info

Classes

Name Children Inherits
NestedDictLoader
jinjarope.configloaders
A jinja loader for loading templates from nested dicts.
TemplateFileLoader
jinjarope.configloaders
A jinja loader for loading templates from config files.

    🛈 DocStrings

    NestedDictLoader

    Bases: LoaderMixin, BaseLoader

    A jinja loader for loading templates from nested dicts.

    This loader allows to access templates from nested dicts. Can be used to load templates defined with markup like TOML.

    Examples:

    [example]
    template = "{{ something }}"
    
    content = tomllib.load(toml_file)
    loader = NestedDictLoader(content)
    env = Environment(loader=loader)
    env.get_template("example/template")
    

    Source code in src/jinjarope/configloaders.py
    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
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    class NestedDictLoader(loaders.LoaderMixin, jinja2.BaseLoader):
        """A jinja loader for loading templates from nested dicts.
    
        This loader allows to access templates from nested dicts.
        Can be used to load templates defined with markup like TOML.
    
        Examples:
            ``` toml
            [example]
            template = "{{ something }}"
            ```
            ``` py
            content = tomllib.load(toml_file)
            loader = NestedDictLoader(content)
            env = Environment(loader=loader)
            env.get_template("example/template")
            ```
        """
    
        ID = "nested_dict"
    
        def __init__(self, mapping: NestedMapping):
            """Constructor.
    
            Args:
                mapping: A nested dict containing templates
            """
            super().__init__()
            self._data = mapping
    
        def __repr__(self):
            return utils.get_repr(self, mapping=self._data)
    
        def list_templates(self) -> list[str]:
            return list(iterfilters.flatten_dict(self._data).keys())
    
        def get_source(
            self,
            environment: jinja2.Environment,
            template: str,
        ) -> tuple[str, str | None, Callable[[], bool] | None]:
            data: Any = self._data
            try:
                for part in template.split("/"):
                    data = data[part]
                assert isinstance(data, str)
            except (AssertionError, KeyError) as e:
                raise jinja2.TemplateNotFound(template) from e
            return data, None, lambda: True  # type: ignore[return-value]
    

    __init__

    __init__(mapping: NestedMapping)
    

    Constructor.

    Parameters:

    Name Type Description Default
    mapping NestedMapping

    A nested dict containing templates

    required
    Source code in src/jinjarope/configloaders.py
    39
    40
    41
    42
    43
    44
    45
    46
    def __init__(self, mapping: NestedMapping):
        """Constructor.
    
        Args:
            mapping: A nested dict containing templates
        """
        super().__init__()
        self._data = mapping
    

    TemplateFileLoader

    Bases: NestedDictLoader

    A jinja loader for loading templates from config files.

    This loader allows to access templates from config files. Config files often often resemble nested dicts when getting loaded / deserialized.

    The loader will load config file from given path and will make it accessible in the same way as the NestedDictLoader. (esp. TOML is well-suited for this)

    Config files can be loaded from any fsspec protocol URL.

    Examples:

    loader = TemplateFileLoader("http://path_to_toml_file.toml")
    env = Environment(loader=loader)
    env.get_template("example/template")
    
    loader = TemplateFileLoader("path/to/file.json")
    env = Environment(loader=loader)
    env.get_template("example/template")
    

    Source code in src/jinjarope/configloaders.py
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    class TemplateFileLoader(NestedDictLoader):
        """A jinja loader for loading templates from config files.
    
        This loader allows to access templates from config files.
        Config files often often resemble nested dicts when getting loaded / deserialized.
    
        The loader will load config file from given path and will make it accessible in the
        same way as the `NestedDictLoader`. (esp. TOML is well-suited for this)
    
        Config files can be loaded from any fsspec protocol URL.
    
        Examples:
            ``` py
            loader = TemplateFileLoader("http://path_to_toml_file.toml")
            env = Environment(loader=loader)
            env.get_template("example/template")
            ```
            ``` py
            loader = TemplateFileLoader("path/to/file.json")
            env = Environment(loader=loader)
            env.get_template("example/template")
            ```
        """
    
        ID = "template_file"
    
        def __init__(
            self,
            path: str | os.PathLike[str],
            fmt: Literal["toml", "json", "ini", "yaml"] | None = None,
            sub_path: tuple[str, ...] | None = None,
        ):
            """Constructor.
    
            Args:
                path: Path / fsspec protocol URL to the file
                fmt: Config file format. If None, try to auto-infer from file extension
                sub_path: An optional tuple of keys describing the "dictionary path" inside
                          the file
            """
            self.path = upath.UPath(path)
            text = envglobals.load_file_cached(self.path)
            file_fmt = fmt if fmt else self.path.suffix.lstrip(".")
            assert file_fmt in ["json", "toml", "yaml", "ini"]
            mapping = serializefilters.deserialize(text, fmt=file_fmt)  # type: ignore[arg-type]
            for part in sub_path or []:
                mapping = mapping[part]
            super().__init__(mapping=mapping)
            self._data = mapping
    
        def __repr__(self):
            path = self.path.as_posix()
            return utils.get_repr(self, path=path)
    

    __init__

    __init__(
        path: str | PathLike[str],
        fmt: Literal["toml", "json", "ini", "yaml"] | None = None,
        sub_path: tuple[str, ...] | None = None,
    )
    

    Constructor.

    Parameters:

    Name Type Description Default
    path str | PathLike[str]

    Path / fsspec protocol URL to the file

    required
    fmt Literal['toml', 'json', 'ini', 'yaml'] | None

    Config file format. If None, try to auto-infer from file extension

    None
    sub_path tuple[str, ...] | None

    An optional tuple of keys describing the "dictionary path" inside the file

    None
    Source code in src/jinjarope/configloaders.py
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    def __init__(
        self,
        path: str | os.PathLike[str],
        fmt: Literal["toml", "json", "ini", "yaml"] | None = None,
        sub_path: tuple[str, ...] | None = None,
    ):
        """Constructor.
    
        Args:
            path: Path / fsspec protocol URL to the file
            fmt: Config file format. If None, try to auto-infer from file extension
            sub_path: An optional tuple of keys describing the "dictionary path" inside
                      the file
        """
        self.path = upath.UPath(path)
        text = envglobals.load_file_cached(self.path)
        file_fmt = fmt if fmt else self.path.suffix.lstrip(".")
        assert file_fmt in ["json", "toml", "yaml", "ini"]
        mapping = serializefilters.deserialize(text, fmt=file_fmt)  # type: ignore[arg-type]
        for part in sub_path or []:
            mapping = mapping[part]
        super().__init__(mapping=mapping)
        self._data = mapping