Extract the first image from a post in Jekyll

This post was published in 2015 and is kept here for reference. It may contain information that's outdated or inaccurate.

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!), so how could I automate this?

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:"<img " %}
{% for image in images %}
  {% if image contains 'src=' %}
    {% assign imageMarkup = image | split:">" | first %}
    <img {{ imageMarkup }}>
    {% 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.

This post is also available in plain text

[Archived comments]

iziy commented

a good way~. but i’m just need the src

[Comments]

Want to comment? You can do so via Github.
Comments via Github are currently closed.

[Webmentions]

Want to reply? I've hooked up Webmentions, so give it a go!