Max Glenister

Blog & IndieWeb • 1 min read Plain text

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!), 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.

  • Blog & IndieWeb · shares #jekyll
    Moving to GitHub Actions (and adding .txt posts)

    This year I moved the blog from GitHub Pages’ built-in Jekyll to a GitHub Actions workflow, then added .txt URL support for posts. Inspired by Terence Eden’s blog post about text-only websites.

    January 2026 • 4 min read
  • Data & Experiments · shares #jekyll
    The Movies I Watched in 2022

    Through 2022 I kept track of most the movies I watched. In this post I’ll talk about how I took that data and, combined with the OMDb API, used the data with Jekyll.

    January 2023 • 4 min read
  • Blog & IndieWeb · shares #jekyll
    Adding support for Webmentions

    I’ve added Webmention support to the posts on this blog. Webmentions are a method for websites to know that they’ve been linked to (or mentioned) from elsewhere on the web.

    April 2022 • 3 min read

Discussion

  • I

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

Join the conversation

Reply from your own site with a Webmention (how?).

Webmentions last fetched 14 November 2026, 10:07