Extract the first image from a post in Jekyll
================================================================================
I decided that I want to show an image next to posts in my “article list” type
pages in Jekyll.
It would be tedious to go through each post and add a piece of Yaml frontmatter
to indicate a “post image”
(even though I had this at one point in the past (https://blog.omgmog.net/post/adding-more-post-metadata-to-jekyll-with-yaml/)!),
so how could I automate this?
[IMAGE: https://blog.omgmog.net/images/tooth-pull.png]
All of my posts exist as Markdown in the codebase, but Jekyll parses this to
HTML when generating the {{ post }} object. This chunk of HTML can in turn be
parsed/split to find the first occurance of an image, and grab it:
{% assign images = post.content | split:"
" | first %}
{% break %}
{% endif %}
{% endfor %}
Once the logic for extracting the first image is sorted out, you simply need to
throw that in to a file (I’m using _post_image.html) and then include it where
you would like the image to appear.
================================================================================
Published July 30, 2015
Generated from the original post:
https://blog.omgmog.net/post/extract-the-first-image-from-a-post-in-jekyll/
Max Glenister is an interface designer and senior full-stack developer from
Oxfordshire. He writes mostly about front-end development and technology.
- Mastodon: https://indieweb.social/@omgmog
- Github: https://github.com/omgmog
- Reddit: https://reddit.com/u/omgmog
- Discord: https://discordapp.com/users/omgmog#6206