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.
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):
Length: {{ collections.posts | length }}, what does it show?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.
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):
Length: {{ collections.posts | length }}, what does it show?Length: {{ postslist | length }}, what does it show?