Skip to content

Instantly share code, notes, and snippets.

@mikeygee
Created May 7, 2012 07:45
Show Gist options
  • Save mikeygee/2626538 to your computer and use it in GitHub Desktop.
Save mikeygee/2626538 to your computer and use it in GitHub Desktop.
truncate blog posts in jekyll
<!-- using the truncate filter -->
{% for post in site.posts limit:10 %}
<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
<span class="post-date">{{ post.date | date: "%B %d, %Y" }}</span>
{% 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 %}
<hr>
{% endfor %}
<!-- using the split filter -->
{% for post in site.posts limit:10 %}
<div class="post-preview">
<h2><a href="{{ post.url }}">{{ post.title }}</a></h2>
<span class="post-date">{{ post.date | date: "%B %d, %Y" }}</span>
{{ 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
@recio-sjogren
Copy link

Thanks! Very useful!

@hardware
Copy link

Great, Thanks !

@danilao
Copy link

danilao commented Sep 8, 2015

Amazing! Thanks!

@WizKIDz
Copy link

WizKIDz commented Nov 24, 2015

very nice 👍

@Joozo
Copy link

Joozo commented Nov 27, 2015

Good. then, you can do this:

---
excerpt_separator: <!--more-->

---

Excerpt
<!--more-->
Out-of-excerpt
// Need remove the <p> tags.
{{ post.excerpt | remove: '<p>' | remove: '</p>' }}

@dotmilk
Copy link

dotmilk commented Sep 6, 2016

{{ post.content | strip_html | truncatewords: 140 }}

Copy link

ghost commented Dec 23, 2016

Thanks for this post! I'm just in trouble like this.

@basanthrzt
Copy link

Awesome!

@ZeroSpree
Copy link

Just what I needed, thank you!

@theimgclist
Copy link

Thank you so much. This really helped!!

@bcetin
Copy link

bcetin commented May 11, 2018

Really useful!

@koenidv
Copy link

koenidv commented Jul 11, 2018

Thank you, simple yet very useful!

@ryoxxyz
Copy link

ryoxxyz commented Aug 28, 2019

Thank you so much! Useful!

Copy link

ghost commented May 6, 2020

{{ post.content | strip_html | truncatewords: 300 }}

Useful, thanks.

@hahwul
Copy link

hahwul commented Oct 20, 2020

Oh, thank you 😁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment