到目前为止,我设法打印了一个包含键值对的列表
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}]
答案 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>
答案 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
类或数据库模型的列表,而不是字典,则可以使用点符号来访问属性