Github generates social images for repositories automatically. This post is about how to accomplish a similar thing for blog posts written in Jekyll.
The Github version looks like this:
I quite like it. It’s simple. It shows the description, the languages, popularity. A nice summary. That’s what I took as a point of reference for generating previews.
This is what the Twitter card for this post looks like:
Still needs a bit of fine-tuning, but much better than not having an image at all.
The instructions here are for a blog running on Jekyll. If you want to replicate it on another platform the general steps are:
Generate html containing only the post preview
And optimize the display of that page to 600px width
Use wkhtmltoimage to capture 600x315 screenshot of the preview
Copy the screenshot to the generated site directory
Set the meta tags
Generate html containing only the post preview
I wanted the previews to be automatically generated based on a flag I set in the front matter of the post.
First, I created the _previews folder, that’ll hold the collection. I added that folder to .gitignore.
Next, I created previews.rb in the _plugins directory. This script copies any posts with auto_image set to true in the front matter whenever files are read.
Because Jekyll would load the files already in the previews directory before this step, it would result in warnings where two documents in the collection contained the same file. To handle that I added a hook that clears the directory.
In order for these files to be picked up, the collection must be added to config.yml:
To render just the preview, I created a preview.html in the layouts directory. I just took the post.html layout and removed everything but the picture, name, title and excerpt. I also adjusted the css a bit to make it fit within a 600x315 container.