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?
To iterate through a list of dictionaries in Jinja template with Python Flask, we use a for loop. to create the parent_list list of dicts. in our Jinja2 template to render the parent_list items in a for loop.
Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.
Jinja can generate any text-based format (HTML, XML, CSV, LaTeX, etc.). A Jinja template doesn't need to have a specific extension: . html , . xml , or any other extension is just fine.
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 %}
this is a bit simpler I think without the use of the slice filter:
{% for post in site.posts | reverse | list[0:4] %} <li>» <a href="/{{ post.url }}">{{ post.title }}</a></li> {% endfor %}
another way is to use the loop controls extension:
{% for post in site.posts | reverse %} {%- if loop.index > 4 %}{% break %}{% endif %} <li>» <a href="/{{ post.url }}">{{ post.title }}</a></li> {%- endfor %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With