My site jonathanyeong.com is built using Eleventy (11ty). 11ty is a static site generator that is flexible with folder structure, data, and templates. This flexibility makes it really easy to add new features or customizations to your site. One feature that I wanted on my site is "Featured Posts". These posts would be the first posts you see on the homepage. They would be handpicked by me. And I wanted to define an ordering for them.
Here's how I set up Featured Posts.
Defining the front matter
11ty allows you define some data in your templates through front matter. Front matter is a block of text between a pair of three dashes. In the example below, I'm using yaml front matter to add some metadata to my post. Here are the 11ty docs for more on Front Matter data.
The two lines relevant to this tutorial are featured_posts: true
and post_weight: 1.0
.
---
date: 2020-12-15T00:00:00-08:00
title: Blog post title
published: true
featured_post: true
post_weight: 1.0
---
<h1>Post Content<h1>
Now that the front matter is squared away we need to create the Featured Posts collection.
Creating the collection
A collection in 11ty is an array of objects. These objects can come from any number of places. Let's break down how we create the featuredPosts
collection.
- Specify the collection that we're creating via
addCollection('featuredPosts'...
. - Get all my markdown posts from
/src/posts/
usinggetFilteredByGlob
. - Filter the collection by
published
andfeatured_post
. These two pieces of data come from the front matter we declared above. - Sort the filtered collection by
post_weight
. The largest post weight will be the first post you see in thefeaturedPosts
collection. - Now you can use this collection in your 11ty templates via
collections.featuredPosts
.
eleventyConfig.addCollection('featuredPosts', collection => {
return collection.getFilteredByGlob('./src/posts/*.md')
.filter(
post => post.data.featured_post && p.data.published
)
.sort((a,b) => {
return a.data.post_weight - b.data.post_weight;
});
});
There's a lot more you can do with collections. If you're interested here are the 11ty docs on collections. I hope this tutorial has inspired you to add featured posts to your site. Or to create your own collection!
I'd love to know if this article helped you or if you found it confusing. Please leave a comment below, I can't wait to read them!
Top comments (0)