The key is understanding and making good use of Eleventy collections and filters.
Assuming you were referring to this Eleventy tutorial by Flamed (since you actually linked to Flamed’s website home page and not any particular post), take note that in the tutorial, blog posts are put in a blog
collection. The tutorial teaches displaying a list of posts from latest to oldest by using a for loop and the reverse
filter, which is built in to Nunjucks, the templating language the tutorial uses. Specifically, the {% for post in collections.blog | reverse %}
line. For loop is how you display items from a colelction.
You can add your own custom filter to your Eleventy configuration file, like .eleventy.js
as instructed in the tutorial, so the first thing you need to do is to add this block of code to your eleventy.js
file, under the eleventyConfig.addPassthroughCopy("./src/css")
line:
eleventyConfig.addFilter("itemLimit", function(array, maximum) {
return array.slice(0, maximum);
});
You can give an Eleventy filter whatever name you want. In this example, I named the filter itemLimit
.
Eleventy is written in JavaScript, so you can create custom filters by writing JavaScript functions. In this filter that limit the number of collection items to display, you can use JavaScript’s slice()
method.
Now that you have set up a filter to limit the number of collection items to display, add a for loop to your home page for your blog
collection and add the itemLimit
filter after the reverse
filter, and then add a content
data variable to display pors content, so your final code to display your latest blog post should be like this:
{% for post in collections.blog | reverse | itemLimit(1) %}
<h1>{{ post.data.title }}</h1>
{{ post.content | safe }}
{% endfor %}
The (1)
is necessary to tell the itemLimit
fliter how many items you want to display, and since you just want to show the latest blog post, you just need to set it as 1.