How to get Auto-Generated Excerpts with Markdown Converted to HTML in Jekyll

17 Oct 2013

Jekyll is quite flexible in terms of what you can do with it. The templating system is both a source of joy and a source of frustration for me as I continue to tweak my website to my liking and run into things that don't quite work the way I'd expect.

For example, blog posts such as this can have "exerpts." You can refer to this in the various templates using {{ post.excerpt }} You can either specify the excerpt in the post's YAML Front Matter, use a plugin that enables this functionality differently, or (at least in Jekyll 1.2.1) let Jekyll auto-generate this for you based on the first paragraph of the post.

The problem with Jekyll's automated generation of a post excerpt--it doesn't convert markdown into HTML. Which means that any markup or links I've put in that first paragraph don't get propagated to the post excerpt.

Why do I care about this? My regular RSS feed is the full post content, but there are a few situations like with ADN Pourover that I only want to feed it a paragraph of text at the most. But I still want links and other markup to propagrate and not be in Markdown format. And I want the experpt to be auto-generated.

And so we have a problem that, as it turns out, as a pretty easy solution.

As I said before, {{ post.excerpt }} is converted from Karkdown to HTML automatically. The problem becomes: how do I get just the first line? I tried using split based on a line break, but that didn't exactly work.

Turns out, I can split it based on the closing paragraph tag in HTML: </p>. I have a line in the relevant .xml file like so:

{% assign desc = post.content | split: '</p>' %}

This takes post.content, assigns that value to the variable desc which gets turned into an array of sorts using the "split" function based on the delimeter </p>.

This effectively makes the first paragraph something I can refer to in my .xml file with {{ desc.first }}. This lacks the closing </p>, but it's easy enough to add in like so:

So now I get what I want: a fully HTMLified post excerpt without having to do any explicit definition of one in my post.

And this, my friends, is what I like about Jekyll. Even though it's definitely not as easy as a Wordpress install, it ends up being a pretty flexible framework you can make do a lot of things for you.

Edit: As a postscript to this, actually encoding the Liquid markdown tags in this was was proving to be challenging until I used the {% raw %} and {% endraw %} tags to tell the Liquid templating system to knock it off. :)