Conditional on file existing

This commit is contained in:
Sam Bull 2026-04-13 00:44:18 +01:00
commit fb328475c7
3 changed files with 69 additions and 1 deletions

View file

@ -592,6 +592,17 @@ def configure_settings(settings: Settings) -> Settings:
else:
raise Exception("Could not find the theme {}".format(settings["THEME"]))
# Clear CSS_FILE if the file doesn't exist in the theme
css_file = settings.get("CSS_FILE")
if css_file:
theme = settings["THEME"]
static_paths = settings.get("THEME_STATIC_PATHS", ["static"])
if not any(
os.path.isfile(os.path.join(theme, sp, "css", css_file))
for sp in static_paths
):
settings["CSS_FILE"] = ""
# standardize strings to lowercase strings
for key in ["DEFAULT_LANG"]:
if key in settings:

View file

@ -133,6 +133,61 @@ class TestTemplateInheritance(LoggedTestCase):
self.assertNotIn("Proudly powered by", content)
self.assertIn("New footer", content)
def test_simple_theme_no_css_link(self):
"""The simple theme has no static/css/ directory, so the CSS_FILE
link should not be rendered."""
settings = read_settings(
path=None,
override={
"THEME": "simple",
"PATH": CONTENT_DIR,
"OUTPUT_PATH": self.temp_output,
"CACHE_PATH": self.temp_cache,
"SITEURL": "http://example.com",
},
)
pelican = Pelican(settings=settings)
mute(True)(pelican.run)()
with open(os.path.join(self.temp_output, "test-md-file.html")) as f:
content = f.read()
self.assertNotIn("/theme/css/main.css", content)
def test_child_theme_with_css_file(self):
"""A child theme that provides static/css/main.css should have the
CSS_FILE link rendered."""
# Add a CSS file to the child theme
css_dir = os.path.join(self.temp_theme, "static", "css")
os.makedirs(css_dir)
with open(os.path.join(css_dir, "main.css"), "w") as f:
f.write("body { margin: 0; }")
settings = read_settings(
path=None,
override={
"THEME": self.temp_theme,
"PATH": CONTENT_DIR,
"OUTPUT_PATH": self.temp_output,
"CACHE_PATH": self.temp_cache,
"SITEURL": "http://example.com",
},
)
pelican = Pelican(settings=settings)
mute(True)(pelican.run)()
with open(os.path.join(self.temp_output, "test-md-file.html")) as f:
content = f.read()
self.assertIn(
'href="http://example.com/theme/css/main.css"',
content,
)
if __name__ == "__main__":
unittest.main()

View file

@ -9,7 +9,9 @@
{% if SITESUBTITLE %}
<meta name="description" content="{{ SITESUBTITLE }}" />
{% endif %}
<link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/{{ CSS_FILE }}" />
{% if CSS_FILE %}
<link rel="stylesheet" href="{{ SITEURL }}/{{ THEME_STATIC_DIR }}/css/{{ CSS_FILE }}" />
{% endif %}
{% if STYLESHEET_URL %}
<link rel="stylesheet" type="text/css" href="{{ STYLESHEET_URL }}" />
{% endif %}