static-sitenunjuckseleventystatic-site-generation

Get Latest Post To Show on Home Page with Eleventy


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.


Solution

  • 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>