Skip to content

Commit cef4059

Browse files
authored
Merge pull request #205 from cs50/copilot/add-og-description-generation
Generate og:description from page content when not explicitly set
2 parents 04ed1d3 + 06354a3 commit cef4059

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

_layouts/page.html

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,16 @@
1111
<meta content="{{ page.refresh }}" http-equiv="refresh">
1212
{%- endif -%}
1313

14-
<meta property="og:description" content="{{ page.description | default: site.cs50.description }}">
14+
{%- capture description -%}
15+
{%- if page.description -%}
16+
{{- page.description -}}
17+
{%- elsif page.content -%}
18+
{{- page.content | describe -}}
19+
{%- else -%}
20+
{{- site.cs50.description -}}
21+
{%- endif -%}
22+
{%- endcapture -%}
23+
<meta property="og:description" content="{{ description | strip }}">
1524

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

lib/jekyll-theme-cs50.rb

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,45 @@ def md5(input)
9999
end
100100
Liquid::Template.register_filter(MDhash)
101101

102+
# Generate a description from page content
103+
module DescriptionGenerator
104+
def describe(input, max_length = 160)
105+
return "" if input.nil? || input.to_s.strip.empty?
106+
107+
# Convert Markdown to HTML
108+
html = $site.find_converter_instance(::Jekyll::Converters::Markdown).convert(input.to_s)
109+
110+
# Parse HTML and extract text
111+
doc = Nokogiri::HTML5.fragment(html)
112+
113+
# Remove the page's title (i.e., first h1 tag)
114+
doc.css("h1").first&.remove
115+
116+
# Remove any table of contents
117+
doc.css("ul#markdown-toc").first&.remove
118+
119+
# Strip tags
120+
text = doc.text.strip
121+
122+
# Clean up whitespace
123+
text = text.gsub(/\s+/, " ").strip
124+
125+
# Return empty string if no text extracted
126+
return "" if text.empty?
127+
128+
# Truncate to max_length, breaking at word boundary
129+
if text.length > max_length
130+
text = text[0...(max_length - 3)]
131+
last_space = text.rindex(" ")
132+
text = text[0...last_space] if last_space && last_space > 0
133+
text += "..."
134+
end
135+
136+
text
137+
end
138+
end
139+
Liquid::Template.register_filter(DescriptionGenerator)
140+
102141
module Mixins
103142

104143
def initialize(tag_name, markup, options)

0 commit comments

Comments
 (0)