MG


truncating blog posts in Jekyll

May 06, 2012

I was working on my Jekyll blog page and noticed some funky output. It turns out that the content variable returns rendered HTML, and the truncate filter in Liquid was cutting it off in the middle of a <ul> element. I had previously thought the filter operated on the unrendered markdown content.

I wanted a way to just display the first part of longer posts for the blog page without breaking/invalidating my HTML. I googled around and found a couple of hacks, but they seemed unnecessarily complicated. It turns out that a split function was added to the Liquid filters a few months back, so what you can do is insert an HTML comment into your posts, split on the comment, and just display the first element of the resulting array. If you don’t need to truncate, it will display the full post. I had to update my local Jekyll to get the (not so) new split function.

sudo gem update

With the truncate filter, it will break in the middle of an HTML node

{% for post in site.posts limit:10 %}
	<div class="post-preview">
		<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
		<div class="post-date">{{ post.date | date: "%B %d, %Y" }}</div>
		{% if post.content.size > 2000 %}
			{{ post.content | truncatewords: 300 }} <!-- bad! content gives you rendered html and you will truncate in the middle of a node -->
			<a href="{{ post.url }}">read more</a>
		{% else %}
			{{ post.content }}
		{% endif %}
	</div>
	<hr>
{% endfor %}

Updated code with the split filter

{% for post in site.posts limit:10 %}
	<div class="post-preview">
		<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
		<div class="post-date">{{ post.date | date: "%B %d, %Y" }}</div>
		{{ post.content | split:'<!--break-->' | first }}
		{% if post.content contains '<!--break-->' %}
			<a href="{{ post.url }}">read more</a>
		{% endif %}
	</div>
	<hr>
{% endfor %}

In your posts file, put your marker wherever you want to cut off the post for the main blog page

---
layout: post
title: truncate example
---
 
Paragraph 1
 
Paragraph 2
 
<!--break-->
 
Paragraph 3
 
Paragraph 4

UPDATE: Well now, this worked perfectly fine on local Jekyll, but after pushing to github pages, it doesn’t work. I guess for now, I will resort to one of the aforementioned hacks.

UPDATE#2: Apparently this works now on GH pages. Thanks Adam Ralph.