Search code examples
pythonhtmlflaskjinja2werkzeug

How to access each dictionary individually in a list of dictionaries using Jinja2?


I have a Python list of multiple dictionaries in Flask as follows (I have also used List Comprehension to access the dictionaries):

app = Flask(__name__)
class Item:
    def __init__(self, vals):
        self.__dict__ = vals

@app.route('/')
def news_page():
    news = [{ "News" : "ABC", "Link" : "http://exampleabc.com", "Date": "01/03/20" },
           { "News" : "DEF", "Link" : "http://exampledef.com", "Date": "02/03/20" },
           { "News" : "GHI", "Link" : "http://exampleghi.com", "Date": "03/03/20" }]
    return render_template('news_screen.html', news = [Item(i) for i in news])

if __name__ == '__main__':
    app.run(debug = True)

My HTML Template looks like this:

<table>
     {% for dict_item in news %}
          <div>
            <tr> {{ dict_item.News }}  </tr> <br>
            <tr> {{ dict_item.Link }}  </tr> <br>
            <tr> {{ dict_item.Date }}  </tr> 
          </div> 
     {% endfor %}
</table>

This, unfortunately, returns all the three dictionaries (ABC, DEF, GHI), although I want only one at a time so that I can display them on different slides individually.

Current Output:

ABC
http://exampleabc.com
01/03/20

DEF
http://exampledef.com
02/03/20

GHI
http://exampleghi.com
03/03/20

How can I access each dictionary separately so that I can display only the "ABC" News, Link and Date at a time?

Expected Output:

ABC
http://exampleabc.com
01/03/20

Solution

  • You dont need to be write extra code for access each item. Just pass same as dictionary to Jinja Tempalte. here you can modified few little changes.

    @app.route('/')
    def news_page():
        news = [{ "News" : "ABC", "Link" : "http://exampleabc.com", "Date": "01/03/20" },
               { "News" : "DEF", "Link" : "http://exampledef.com", "Date": "02/03/20" },
               { "News" : "GHI", "Link" : "http://exampleghi.com", "Date": "03/03/20" }]
        return render_template('news_screen.html', news = news )
    

    After all if you want to get items in Jinja Template.

    <table>
         {% for dict_item in news %}
              <div>
                <tr> <a href="{{ dict_item.Link }}">{{ dict_item.News }}</a></tr> <br>
                <tr> {{ dict_item.Link }}  </tr> <br>
                <tr> {{ dict_item.Date }}  </tr> 
              </div> 
         {% endfor %}
    </table>
    

    Else if you want to single item in Jinja Template.

    <div class="panel">
          <div class="panel-title"><a href="{{ news[0].Link }}">{{ news[0].News }}</a></div>
          <div class="panel-body">{{news[0].Date}} </div>
    </div>