From 66946fec7e0f622f44384720c137bdbb3bbb90e3 Mon Sep 17 00:00:00 2001 From: Tim Vink Date: Thu, 2 Dec 2021 23:42:00 +0100 Subject: [PATCH] Fix occasional bug in mkdocs theme where print site would break --- mkdocs_print_site_plugin/plugin.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/mkdocs_print_site_plugin/plugin.py b/mkdocs_print_site_plugin/plugin.py index 35a1666..1b3ce18 100644 --- a/mkdocs_print_site_plugin/plugin.py +++ b/mkdocs_print_site_plugin/plugin.py @@ -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 @@ -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): @@ -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): @@ -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")