Get first item in Eleventy Collection

How to get the first item in a given collection using Eleventy (with nunjucks).

Whenever you have a collection of items, within nunjucks there is the ability to choose the first in a collection.

Set a variable to do this and use the | first syntax:

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

Then use it to render your item:

<article>
  <h3>
    <a href="{{ first.url}}">
      {{ first.data.title }}
    </a>
  </h3>
</article>

More than one?

you can also use loop.index if you're only wanting to output a certain number of posts:

{% for item in collections.postsSorted %}
  {# will show the first 3 posts #}
  {% if loop.index<=3 %}
  <h3>
    <a href="{{first.url}}">
      {{ first.data.title }}
    </a>
  </h3>
  {% endif }
{% endfor }

Handy if, like me you’re new to nunjucks.

* I know nunjucks may not be templating flavor of the month, but at the same time it’s likely to be supported in Eleventy for quite a long time so still seems like a good bet until WebC is more fully featured.