Eleventy: Get `n` elements of a collection

Created on 30 Oct 2019  路  6Comments  路  Source: 11ty/eleventy

I think this is easy but I am a beginner and I think I stuck with collection elements listing. I wanted shortlisted elements on the homepage, I used tags but I have 10 elements for each tag and I want to shortlist only 3 on homepage (for each tag). I tried to make something like this (from Eleventy Base Blog):

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

and I added on .eleventy.js

  eleventyConfig.addFilter("head", (array, n) => {
    if( n < 0 ) {
      return array.slice(n);
    }
    return array.slice(0, n);
  });

but it doesn't work, I tried to copy all elements/pages but I think I miss something and my beginner level cant finds it.

education

Most helpful comment

@MisterSocks I don't see anything obviously wrong with what you've posted.

A few things I might suggest checking (if you don't want to use one of the solutions above):

  1. If you don't use the filter, do all posts show?
  2. If you do add Length: {{ collections.posts | length }}, what does it show?
  3. If you do add Length: {{ postslist | length }}, what does it show?

All 6 comments

You don't need any filter for that, just:

{% set atPost = 0 %}
{% for post in collection.posts %}
{% if atPost < 3 %}
{#  do your processing here or include it #}
{% endif%}
{% set atPost = atPost + 1 %}
{% endfor %}

If you want a filter because you use that a lot through your codebase, add a filter. I use a simpler version than yours but it works fine.

// limit filter
eleventyConfig.addFilter("limit", function(array, limit) {
  return array.slice(0, limit);
});

then

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

Your filter should work as far as I can see.

@octoxalis In nunjucks you get an iterator you can test when doing for loops.

{% for post in collection.posts %}
  {% if loop.index0 < 4 %}
  {#  do your processing here or include it #}
  {% endif%}
{% endfor %}

With that said, I quite like using filters for this sort of thing.

@MisterSocks I don't see anything obviously wrong with what you've posted.

A few things I might suggest checking (if you don't want to use one of the solutions above):

  1. If you don't use the filter, do all posts show?
  2. If you do add Length: {{ collections.posts | length }}, what does it show?
  3. If you do add Length: {{ postslist | length }}, what does it show?

@edwardhorsford you're right and do use it but just forgot for a while...

// limit filter
 eleventyConfig.addFilter("limit", function(array, limit) {
 return array.slice(0, limit);
});

yes, it is working , thanks. I cleaned some code and now everything works good.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zachleat picture zachleat  路  3Comments

AjitZero picture AjitZero  路  3Comments

kaloja picture kaloja  路  3Comments

michrome picture michrome  路  3Comments

aaronstezycki picture aaronstezycki  路  3Comments