Get Latest Post To Show on Home Page with Eleventy

1.5k views Asked by At

I'm diving into the static site generators and trying to build a blog out using the basic eleventy blog: https://github.com/11ty/eleventy-base-blog

So far, everything is good, but I'm wondering how to go about to get it to show the latest post on the home/index page.

Right out of the box, it will show the 3 latest links to the posts using nunjucks:

{% set postslist = collections.posts | head(-3) %}
{% set postslistCounter = collections.posts | length %}
{% include "postslist.njk" %}

But what I'm wondering how to get the latest markdown post from the posts directory and see if it can pull that to render.

I am thinking that there's got to be a way to check the date within nunjucks like this (I know this is wrong, but trying to get an idea):

{% if post.date = currdate %}
{% include "posts.njk" %}
{% endif %}

Anyways, I know it's possible, but I'm still trying to learn and looking to get pointed in the right direction.

2

There are 2 answers

3
Raymond Camden On BEST ANSWER

I think this could work for you:

{% set postslist = collections.posts | head(-3) %}

<h1>Latest Post</h1>
{{ postslist[0].templateContent | safe }}

I basically just use the templateContent variable of the first post. I moved that set command higher in the template so I could use another H3. Here's my entire file:

---
layout: layouts/home.njk
eleventyNavigation:
  key: Home
  order: 1
---

{% set postslist = collections.posts | head(-3) %}

<h1>Latest Post</h1>
{{ postslist[0].templateContent | safe }}

<h1>Latest 3 Posts</h1>

{% set postslistCounter = collections.posts | length %}
{% include "postslist.njk" %}

<p>More posts can be found in <a href="{{ '/posts/' | url }}">the archive</a>.</p>
0
StefanGreve On

The accepted answer is outdated, because Nunjucks removed the built-in head filter. You can use first filter to select the most recent blog post like this:

{% set mostRecent = collections.posts | first %}

To select the first (or last) n posts, loop over collections.posts:

{% set top = 3 %}
{% for post in collections.posts %}
  {# ensure that top does not exceed the length of the collection #}
  {% if (loop.index <= top) and (top <= loop.length) %}
    <div>{{ post.title }}</div>
  {% endif %}
{% endfor %}

Use the reverse filter for the other direction.

See also: http://mozilla.github.io/nunjucks/templating.html#for