11ty / eleventy-plugin-rss

A pack of Eleventy plugins for generating an RSS feed.
https://www.11ty.dev/docs/plugins/rss/
MIT License
92 stars 22 forks source link

Limiting the number of rss channels when displaying #29

Closed exaline-ru closed 2 years ago

exaline-ru commented 2 years ago

How to limit the number of rss feeds when outputting (for example generate only 10 latest content)?

pdehaan commented 2 years ago

@exaline-ru, You could use a custom filter which slices the array/collection.

For example:

  eleventyConfig.addFilter("head", function (arr=[], count=1) {
    if (count < 0) {
      // If the count is a negative value, get the last `n` items.
      return arr.slice(count);
    }
    // Else the count is positive, get the first `n` items.
    return arr.slice(0, count);
  });

Then in your RSS feed template, something like this (I stole the general code from the https://www.11ty.dev/docs/plugins/rss/#sample-atom-feed-template template):

{%- for post in collections.blog | head(-10) %}
...
{% endfor %}

So the head(-10) grabs the last 10 items in the blog collection (so if you had 50 posts, it'd be post 45-49; assuming zero indexed array). But it all might depend on whether your collection is pre-sorted. My fake data set was just an array of 50 numbers from 0-49, but if your collection already is sorted w/ newest first, you could probably use head(10) instead to grab the first ten items instead of the last ten items. 🤷

pdehaan commented 2 years ago

You might be able to use the Nunjucks built-in batch and first filters, instead of using a custom filter:

{% for post in collections.blog | batch(10) | first %}
...
{% endfor %}
exaline-ru commented 2 years ago

Thanks for the tips. Decided differently: (for 10 contents)

{% set allposts = collections.posts | limit(10) %} {% for post in allposts %} ... {% endfor %}

and:

{% for post in collections.posts %} {% if loop.index < 10 %} ... {% endfor %}

zachleat commented 2 years ago

Sounds like this one is resolved, thanks folks!