From abe865cfd7ceb8a78fa564857b1764def0b0cbaf Mon Sep 17 00:00:00 2001 From: Sergei Borisov Date: Wed, 27 Sep 2023 14:27:42 +0300 Subject: [PATCH] Add file system loader to jinja contex Ability to use `include` and/or `import` jinja clauses in the markdown --- markdownextradata/plugin.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/markdownextradata/plugin.py b/markdownextradata/plugin.py index 25bca2c..5ffb5bd 100644 --- a/markdownextradata/plugin.py +++ b/markdownextradata/plugin.py @@ -31,6 +31,7 @@ class MarkdownExtraDataPlugin(BasePlugin): config_scheme = ( ("data", mkdocs.config.config_options.Type(str_type, default=None)), + ("base_dirs", mkdocs.config.config_options.Type(list, default=None)), (JINJA_OPTIONS, mkdocs.config.config_options.Type(dict, default={})) ) @@ -101,7 +102,8 @@ def on_page_markdown(self, markdown, page, **kwargs): # Initialize this mkdocs config and Jinja2 env def on_config(self, mkdocsConfig, **kwargs): jinja_options = self.config[self.JINJA_OPTIONS] - self.env = jinja2.Environment(undefined=jinja2.DebugUndefined, **jinja_options) + loader = self.get_file_loader(mkdocsConfig) + self.env = jinja2.Environment(undefined=jinja2.DebugUndefined, loader=loader, **jinja_options) self.mkdocsConfig = mkdocsConfig # Apply Jinja2 substitution to specified string @@ -115,3 +117,19 @@ def apply_template(self, template_string): "'extra' dictionary. Check the README for more information.") raise + def get_file_loader(self, mkdocsConfig) -> jinja2.BaseLoader: + docs_dir = mkdocsConfig["docs_dir"] + base_dirs = self.config.get("base_dirs", []) + if not base_dirs: + return jinja2.FileSystemLoader(docs_dir) + + if isinstance(base_dirs, str): + base_dirs = base_dirs.split(',') + + base_dirs = [os.path.join(docs_dir, i) for i in base_dirs] + + base_dirs.insert(0, docs_dir) + + data_source_loaders = [jinja2.FileSystemLoader(i) for i in base_dirs] + return jinja2.ChoiceLoader(data_source_loaders) +