Han
Han

Reputation: 131

How to print a dictionary within a list in jinja2?

So far I managed to print a list with key-value pairs

attendance list
{'Student ID': '15000000', 'Class attended': 1,'Total average score': 0.8}

code in html

 {% for key,value in attendance.items() %}
    <h1>{{key}}</h1>
    <h2>Value: {{value}}</h2>
 {% endfor %}

How do I print for this list?

allAttendance List
[{'Student ID': '15000000', 'Class attended': 1, 'Total average score': 0.8}, {'Student ID': '15000001', 'Class attended': 8, 'Total average score': 6.4}]

Upvotes: 0

Views: 295

Answers (2)

Ajax1234
Ajax1234

Reputation: 71451

I suggest using a class to represent the data an HTML table for clean formatting:

class Data:
  def __init__(self, d):
     self.__dict__ = {a.lower().replace(' ', '_'):b for a, b in d.items()}

class Fulldata:
   def __init__(self, data):
      self.data = data
   def __iter__(self):
      for i in self.data:
          yield Data(i)


s = [{'Student ID': '15000000', 'Class attended': 1, 'Total average score': 0.8}, {'Student ID': '15000001', 'Class attended': 8, 'Total average score': 6.4}]
final_data = Fulldata(s)

Then, pass final_data to the templating object, and in your HTML, create the table:

<h1>Attendance List</h1>
<table>
 <tr>
   <th>Id</th>
   <th>Attendence</th> 
  <th>Average Score</th>
</tr>
{%for student in final_data%}
<tr>
  <td>{{student.student_id}}</td>
  <td>{{student.class_attended}}</td> 
  <td>{{student.total_average_score}}</td>
</tr>
{%endfor%}
</table>

enter image description here

Upvotes: 1

OneCricketeer
OneCricketeer

Reputation: 191733

Personally, I would try something like this

 {% for student in allAttendance %}
    <h1>ID: {{student["Student ID"]}}</h1>
    <p>Attended: {{student["Class attended"]}}; Score: {{student["Total average score"]}}</p>
 {% endfor %}

You can add {% for key,value in student.items() %} if you wanted, but I would do it after the h1 (though, you would then need to skip the ID key)

Note: If you had a list of some Student class, or database models, rather than dictionaries, you could use dot-notation to access attributes

Upvotes: 1

Related Questions