Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access part of a list in Jinja2

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?

like image 647
Jesse Spielman Avatar asked Oct 31 '10 07:10

Jesse Spielman


People also ask

How do I iterate through a list in Jinja?

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.

What is the difference between Jinja and Jinja2?

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.

Which data type we use for send values in Jinja?

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.


2 Answers

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 %} 
like image 126
joemurphy Avatar answered Oct 04 '22 00:10

joemurphy


this is a bit simpler I think without the use of the slice filter:

{% for post in site.posts | reverse | list[0:4] %}   <li>&raquo; <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>&raquo; <a href="/{{ post.url }}">{{ post.title }}</a></li> {%- endfor %} 
like image 26
Rico Schiekel Avatar answered Oct 03 '22 23:10

Rico Schiekel