如何在jinja2的列表中打印字典?

时间:2018-04-12 02:48:49

标签: python html jinja2

到目前为止,我设法打印了一个包含键值对的列表

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

html中的代码

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

如何打印此列表?

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

2 个答案:

答案 0 :(得分:1)

我建议使用一个类来表示HTML表的数据以进行干净的格式化:

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)

然后,将final_data传递给模板对象,并在HTML中创建表格:

<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

答案 1 :(得分:1)

就个人而言,我会尝试这样的事情

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

如果您愿意,可以添加{% for key,value in student.items() %},但我会在h1后执行此操作(但是,您需要跳过ID键)

注意:如果您有一些Student类或数据库模型的列表,而不是字典,则可以使用点符号来访问属性