Front End Collision

Blog of software engineer Josh Beam

How to show a summary of your post with Jekyll

23 March 2015 — Josh Beam — jekyll snippet

All Posts
In this little snippet, we're going to explore an option to show a summary of your blog post or article, if you're using the awesome static-site generator called Jekyll.

I am using the static-site generator Jekyll to compile my website into a bunch of static files (the main benefit being a generally more secure and potentially quicker website due to a lack of server round-trips to a database).

I ran across several solutions for displaying a summary or excerpt of the post in the main blog page (if you’re using the basic Jekyll theme that comes standard, it’ll probably be your index.html).

Anyway, the solution I came up with is meant to allow me to control what part of the post I want to display as an excerpt. If I don’t choose a part of the post, that’s okay, it just displays a default excerpt.

If you didn’t know, Jekyll uses Liquid for its templating.

Example:

<!-- index.html -->
<p class="post-excerpt">

{% if post.content contains '<!--excerpt.start-->' and post.content contains '<!--excerpt.end-->' %}
	{{ ((post.content | split:'<!--excerpt.start-->' | last) | split: '<!--excerpt.end-->' | first) | strip_html | truncatewords: 20 }}
{% else %}
	{{ post.content | strip_html | truncatewords: 20 }}
{% endif %}

</p>

<!-- _posts/some-random-post.html -->
<p>
Here's all my content, and <!--excerpt.start-->here's where I want my summary to begin, and this is where I want it to end<!--excerpt.end-->.
</p>

If I don’t add the comments in the post, the template with simply extract the content of the post, strip the HTML tags, and truncate it 20 words, followed by an ellipsis ....