Was working on improving this jekyll blog, when I cam across the issue of truncating blog post for the front page view.

By default it only shows the first paragraph with ``. However I wanted to show pictures. Thus...

There is 3 approaches I could have done here.

  1. Limit post by number of words. But this may cut off html tags, thus messing up the presentation. {{ post.content | truncatewords: 50 }} or you could try stripping html, but you lose images. which is unacceptable to me. {{ post.content | strip_html | truncatewords: 50 }}

  2. Truncate by paragraph like shown in this stack overflow page. This is not as bad, but it lack the ability to control presentation.

    {%- set truncatedContent = '' %}
    {%- set paragraphs = post.content | split:'</p>' %}
    {%- for paragraph in paragraphs limit:N %}
    	{{ truncatedContent | append: paragraph }}
    	{{ truncatedContent | append: '</p>' }}
    {%- endfor %}
  3. Truncate by splitting at <!--more--> (which is how wordpress typically does things). Here is an example from http://mikeygee.com/blog/truncate.html :

    {%- 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 %}
    {%- endfor %}

I chose option 3, since it gives most flexibility. However my issue with this previous code is that it doesn't stick to the standard of wordpress using <!--more--> as the tag. Also if I forget to place the <!--more--> tag, then the entire post just gets dumped into the front page. This is undesirable. Thus the code was customised as shown below to correct for this issue.

If the <!--more--> tag is detected, then an excerpt based on <!--more--> is used. If <!--more--> is not detected then by default the first paragraph is used instead.

Use me!

{%- if post.content contains '<!--more-->' %}
	{{ post.content | split:'<!--more-->' | first }}
{%- else %}
	{{ post.excerpt }}
{%- endif %}
	<a href="{{ post.url }}">read more</a>

If you like this, then dont forget to credit the modification to me, and the original code to mikeygee http://mikeygee.com/blog/truncate.html .


  • http://sarathlal.com/escape-liquid-template-tags-in-jekyll-posts/ -- used this to escape/comment out liquid template code in jekyll
  • http://mikeygee.com/blog/truncate.html