Alice_inwonderland
Alice_inwonderland

Reputation: 348

Render dictionary's key-value pairs using Jinja in html

I'm building a flask app which generates a dictionary object as followed:

file_dict = {'file1':'url_file1' , 'file2':'url_file2, 'file3':'url_file3'}

This object is sent to html through:

return render_template('file.html', keys= file_dict.keys(), values=file_dict.get(file_dict.keys())) 

What I want to do is to iterate through the dictionary and show the files as dictionary keys in hyperlink using the corresponding links in the dictionary's values.

I have tried variations of loops but jinja always prints out the entire dictionary:

<div class="content-section">
     <h3>Current Balance Sheet Statements on file</h3>
          <ul class="list-group">
              <a href="{{ values }}"> {{ keys }} </a>
          </ul>
</div>

Please advise. Thank you.

Upvotes: 0

Views: 1985

Answers (1)

djnz
djnz

Reputation: 2050

A simple way to iterate through a dict, is using the items() method. This will return a Key, Value pair which you can then use in your Jinja:

In your view, just pass the whole dict to render_template:

return render_template('file.html', file_dict=file_dict)

And in your view, add a for loop to display each item (Key, Value pair) in your dict:

<div class="content-section">
    <h3>Current Balance Sheet Statements on file</h3>
    <ul class="list-group">
        {% for key, value in file_dict.items() %}
        <li><a href="{{ value }}">{{ key }}</a></li>
        {% endfor %}
    </ul>
</div>


Upvotes: 1

Related Questions