Let’s take a look at how to use and modify post excerpt for Jekyll generated blog.
Post excerpts
To display post excerpt in a post list, simply use excerpt variable on a post.
{{ post.excerpt }}
By default, excerpt variable displays the first paragraph of post like this:
Customize excerpt length
To customize the length of excerpt, add “excerpt_separator” to post’s front matter or _config.yml.
excerpt_separator: <!–more–>
Then add <!–more–> in a post, wherever you want to split the content.
If you don’t add or forget to add a separator to your post, “excerpt” variable shows a whole content of your post.
Another way to show excerpts
There is another way to show post excerpts, using Liquid filters.
truncatewords shortens a string down to the number of words specified as an argument, and add an ellipsis(…) at the end of the string.
For example, this will display first 30 words of a post
{{ post.content | truncatewords: 30 }}
like this:
However, downside of using truncatewords filter is, if any headers are included within the specified number of words, the result doesn’t look right, like this:
This is not cool.
And the same thing happens when you use excerpt_separator, if you add separator after some header in you post.
So, in some case truncatewords filter works, in other case it doesn’t. For now, this blog uses “excerpt” variable to display post excerpts. I will continue working on this.
Use summary field (Updated)
You can use summary field instead of post excerpt. Here’s how to:
- Add summary field to post front matter and input desired text/excerpt for the post. This can be completely different from the default post excerpt, which is usually the first paragraph.
- In layout file where you retrieve posts list, use {{ post.summary }} variable to display post’s summary field.
Example code:
// front matter
---
title: My Awesome post
summary: "Write what is this post about or post excerpt here."
---
<!-- in post retrieval loop -->
<div class="content">
{% if post.summary %}
{{ post.summary }}
{% else %}
{{ post.excerpt }}
{% endif %}
</div>
In this case, if summary field is empty or not defined in front matter, default post excerpt is displayed.
If interested, you can read more about front matter.
→ Jekyll: How to Use Front Matter
Hope these solutions help. See you