Search code examples
pythonflaskjinja2

How to access and display specific list item in flask


Like in python we can able to access element of the list by mentioning its position , can we do that similar thing in flask

Example main.py

def line():
    list=[1,2,3,4,5]
    return render_template('list.html',list=list)

list.html

{% for item in list %}
  <li>{{item}} </li>
{% endfor %}

As we know the above line will print entire list. But can we print only the item of list , that's is in the 2nd position

something like this:

{% for item in list %}
      <li>{{item[2]}} </li>
 {% endfor %}

should only display:

3

Do you have any ideas?? how to do to it in flask using Jinja template


Solution

  • here is your answer

    <li>{{list[2]}}</li>
    

    No need to print the whole list if you don't want to, just pass the index.