Finding the newest blog post in 11ty (nunjucks)
This is one of those things I had to think through because it is really a Javascript question and not a template question, so the first trick is to get in the right mind set. Once you stop thinking about templates, you can focus on what needs to be done.
The real question turns out to be: How do I get the last N elements in an array?
Like this:
{%- for post in collections.blog | reverse -%}
{%- if loop.index0 < 1 -%}
{{ Write all the things }}
{%- endif -%}
{%- endfor -%}
- Use a filter to reverse the sort order of your blog collection (or whatever you tag your blog collection with),
- grab the entry with an index position of zero,
- write out your values.
Increase the value in the conditional to write out more. For instance, the first three would be loop.index0 < 3
.
Simple. No fancy hoop jumping. No racing around trying plugins that claim to help with such things.
So simple no one bothered to write it down and I had it figure it out myself.
Okay, there is probably a better way to do that that doesn't involve walking the entire collection, and some day I will figure it out. But since it only affects build time…