Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add file system loader to jinja contex #48

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion markdownextradata/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={}))
)

Expand Down Expand Up @@ -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
Expand All @@ -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)