Jekyll is a popular static site generator used for creating blogs and websites. While it doesn't have a built-in widget system like WordPress, you can still add custom features such as a recent posts sidebar. This guide will walk you through creating a custom sidebar widget for recent posts in Jekyll.
Understanding Jekyll's Layout and Includes
Jekyll uses layouts and includes to organize site components. To add a sidebar with recent posts, you'll create an include file that fetches and displays the latest posts, then insert it into your layout.
Creating the Recent Posts Include
Start by creating a new include file named recent-posts.html in the _includes directory of your Jekyll site. This file will contain the logic to list recent posts.
{% comment %} Fetch the latest 5 posts {% endcomment %}
{% assign recent_posts = site.posts | sort: 'date' | reverse | slice: 0, 5 %}
Recent Posts
{% for post in recent_posts %}
- {{ post.title }}
{% endfor %}
Inserting the Sidebar into Your Layout
Open your main layout file, typically default.html in the _layouts folder. Insert the include where you want the recent posts widget to appear, such as in the sidebar section.
{% include recent-posts.html %}
Customizing the Widget
You can customize the number of posts displayed by changing the slice: 0, 5 parameter in recent-posts.html. Additionally, you can style the list with CSS to match your site’s design.
Conclusion
Adding a custom recent posts sidebar in Jekyll involves creating an include file and inserting it into your layout. This method is flexible and allows you to tailor your site’s navigation to your needs, enhancing user experience.