From 9695241b2694ed2bdab48554d6f1de22c372c3c5 Mon Sep 17 00:00:00 2001 From: "David J. Malan" Date: Sun, 9 Nov 2025 00:21:11 -0500 Subject: [PATCH] automatically inferring og:description --- _layouts/page.html | 8 +++--- lib/jekyll-theme-cs50.rb | 54 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 5 deletions(-) diff --git a/_layouts/page.html b/_layouts/page.html index 5d3d8b5..4d76c23 100644 --- a/_layouts/page.html +++ b/_layouts/page.html @@ -7,11 +7,9 @@ - {%- if page.refresh -%} + {%- if page.refresh %} - {%- endif -%} - - + {%- endif %} @@ -25,7 +23,7 @@ {{- site.cs50.title -}} {%- endunless -%} {%- endif -%} - {%- endcapture -%} + {%- endcapture %} diff --git a/lib/jekyll-theme-cs50.rb b/lib/jekyll-theme-cs50.rb index 376aa91..5223189 100644 --- a/lib/jekyll-theme-cs50.rb +++ b/lib/jekyll-theme-cs50.rb @@ -431,6 +431,60 @@ def relative_url(input) end end +Jekyll::Hooks.register [:pages], :post_render do |page| + + # Skip if not HTML + next if page.output_ext != ".html" + + # Parse HTML + doc = Nokogiri::HTML(page.output) + main = doc.at_css("main") + next if main.nil? + + # If page.description + if page.data.key?("description") + description = page.data["description"] + + # Else infer + else + + # Remove the page's title (i.e., first h1 tag) + main.css("h1").first&.remove + + # Remove any table of contents + main.css("ul#markdown-toc").first&.remove + + # Remove any spoilers + main.css("details")&.remove + + # Strip tags + text = main.text.strip + + # Clean up whitespace + text = text.gsub(/\s+/, " ").strip + + # Truncate to max_length, breaking at word boundary + max_length = 160 + if text.length > max_length + description = text[0...(max_length - 3)] + last_space = description .rindex(" ") + description = description[0...last_space] if last_space && last_space > 0 + description += "..." + end + end + + # Inject description + head = doc.at_css("head") + next if head.nil? + meta = Nokogiri::XML::Node.new("meta", doc) + meta["property"] = "og:description" + meta["content"] = CGI.escapeHTML(description) + head.add_child(meta) + + # Update HTML + page.output = doc.to_html +end + Jekyll::Hooks.register [:site], :post_render do |site| # Paths of pages