How do I access part of a list in Jinja2

Jesse Spielman       picture Jesse Spielman · Oct 31, 2010 · Viewed 37.9k times · Source

I'm trying to use the jinja2 templating langauge to return the last n(say, 5) posts in my posts list:

{% for recent in site.posts|reverse|slice(5) %}
    {% for post in recent %}
        <li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
    {% endfor %}
{% endfor %}

This is returning the whole list though. How do you strip the first or last n elements?

Answer

joemurphy picture joemurphy · Apr 22, 2013

I had the same problem too. It's a simple answer. This retrieves the last five items in site.posts:

{% for recent in site.posts[-5:] %}
    {% for post in recent %}
        <li> <a href="/{{ post.url }}">{{ post.title }}</a></li>
    {% endfor %}
{% endfor %}