Skip to content

TemplateFileLoader

Base classes

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

⋔ Inheritance diagram

graph TD
  94142655718992["configloaders.TemplateFileLoader"]
  94142655718000["configloaders.NestedDictLoader"]
  94142653860608["loaders.LoaderMixin"]
  140199010283712["builtins.object"]
  94142650643376["loaders.BaseLoader"]
  94142655718000 --> 94142655718992
  94142653860608 --> 94142655718000
  140199010283712 --> 94142653860608
  94142650643376 --> 94142655718000
  140199010283712 --> 94142650643376

🛈 DocStrings

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

Show source on GitHub