Skip to content

Commit

Permalink
Fix occasional bug in mkdocs theme where print site would break
Browse files Browse the repository at this point in the history
  • Loading branch information
timvink committed Dec 2, 2021
1 parent 2506f5d commit 66946fe
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion mkdocs_print_site_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from mkdocs.structure.files import File
from mkdocs.structure.pages import Page
from mkdocs.utils import write_file, copy_file, get_relative_url, warning_filter
from mkdocs.exceptions import PluginError

from mkdocs_print_site_plugin.renderer import Renderer
from mkdocs_print_site_plugin.utils import flatten_nav, get_theme_name
Expand Down Expand Up @@ -139,6 +140,11 @@ def on_config(self, config, **kwargs):
print_page=self.print_page,
)

# Tracker
# to see if context has been extracted from
# template context
self.context = {}

return config

def on_nav(self, nav, config, files, **kwargs):
Expand Down Expand Up @@ -217,10 +223,23 @@ def on_template_context(self, context, template_name, config, **kwargs):
"""
if not self.config.get("enabled"):
return

# Save the page context
# We'll use the same context of the last rendered page
# And apply it to the print page as well (in on_post_build event)
self.context = context



# Note a theme can have multiple templates
# Found a bug where in the mkdocs theme,
# the "sitemap.xml" static template
# has incorrect 'extra_css' and 'extra_js' paths
# leading to breaking the print page
# at random (when sitemap.xml was rendered last)
# we're assuming here all templates have a 404.html template
# print(f"\nName: {template_name}\nContext: {context.get('extra_css')}")
if template_name == "404.html":
self.context = context


def on_post_build(self, config, **kwargs):
Expand All @@ -232,6 +251,12 @@ def on_post_build(self, config, **kwargs):
if not self.config.get("enabled"):
return

if len(self.context) == 0:
msg = "Could not find a template context.\n"
msg += "Report an issue at https://github.com/timvink/mkdocs-print-site-plugin\n"
msg += f"And mention the template you're using: {get_theme_name(config)}"
raise PluginError(msg)

# Add print-site.js
js_output_base_path = os.path.join(config["site_dir"], "js")
js_file_path = os.path.join(js_output_base_path, "print-site.js")
Expand Down

0 comments on commit 66946fe

Please sign in to comment.