Skip to content

Commit 9695241

Browse files
committed
automatically inferring og:description
1 parent 04ed1d3 commit 9695241

File tree

2 files changed

+57
-5
lines changed

2 files changed

+57
-5
lines changed

_layouts/page.html

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,9 @@
77
<meta charset="utf-8">
88
<meta name="viewport" content="initial-scale=1, width=device-width">
99

10-
{%- if page.refresh -%}
10+
{%- if page.refresh %}
1111
<meta content="{{ page.refresh }}" http-equiv="refresh">
12-
{%- endif -%}
13-
14-
<meta property="og:description" content="{{ page.description | default: site.cs50.description }}">
12+
{%- endif %}
1513

1614
<meta property="og:image" content="{{ page.image | default: site.cs50.image }}">
1715

@@ -25,7 +23,7 @@
2523
{{- site.cs50.title -}}
2624
{%- endunless -%}
2725
{%- endif -%}
28-
{%- endcapture -%}
26+
{%- endcapture %}
2927

3028
<meta property="og:title" content="{{ title }}">
3129

lib/jekyll-theme-cs50.rb

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,60 @@ def relative_url(input)
431431
end
432432
end
433433

434+
Jekyll::Hooks.register [:pages], :post_render do |page|
435+
436+
# Skip if not HTML
437+
next if page.output_ext != ".html"
438+
439+
# Parse HTML
440+
doc = Nokogiri::HTML(page.output)
441+
main = doc.at_css("main")
442+
next if main.nil?
443+
444+
# If page.description
445+
if page.data.key?("description")
446+
description = page.data["description"]
447+
448+
# Else infer
449+
else
450+
451+
# Remove the page's title (i.e., first h1 tag)
452+
main.css("h1").first&.remove
453+
454+
# Remove any table of contents
455+
main.css("ul#markdown-toc").first&.remove
456+
457+
# Remove any spoilers
458+
main.css("details")&.remove
459+
460+
# Strip tags
461+
text = main.text.strip
462+
463+
# Clean up whitespace
464+
text = text.gsub(/\s+/, " ").strip
465+
466+
# Truncate to max_length, breaking at word boundary
467+
max_length = 160
468+
if text.length > max_length
469+
description = text[0...(max_length - 3)]
470+
last_space = description .rindex(" ")
471+
description = description[0...last_space] if last_space && last_space > 0
472+
description += "..."
473+
end
474+
end
475+
476+
# Inject description
477+
head = doc.at_css("head")
478+
next if head.nil?
479+
meta = Nokogiri::XML::Node.new("meta", doc)
480+
meta["property"] = "og:description"
481+
meta["content"] = CGI.escapeHTML(description)
482+
head.add_child(meta)
483+
484+
# Update HTML
485+
page.output = doc.to_html
486+
end
487+
434488
Jekyll::Hooks.register [:site], :post_render do |site|
435489

436490
# Paths of pages

0 commit comments

Comments
 (0)