【发布时间】:2019-01-04 11:56:21
【问题描述】:
我正在尝试使用 django 模板语言生成一个动态 html 表格,但我还没有做到。
这是关于我的 Views.py 和 table.html
的一些信息Views.py
Class table(TemplateView):
template_name = 'table.html'
def get(self, request):
header = {'header':['#', 'chemblID','Preferable Name']}
rows = {'rows':{
'id':[1,2,3],
'chemblid':[534988,31290, 98765],
'prefName':['A', 'B', 'C']}}
return render(request,self.template_name, header,rows)
(数据是硬编码的,因为我还在测试。但是它应该根据用户输入而改变。)
table.html
<table class="table">
<thead>
<tr>
{% for k in header %}
<th>{{k}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
{% for e in r %}
<td>{{e.id}}</td>
<td>{{e.chemblid}}</td>
<td>{{e.prefName}}</td>
{% endfor %}
</tr>
{% endfor %}
</tbody>
</table>
我正在尝试生成这样的东西:
--------------------------------------------------------------
| # | chemblID | Preferable Name |
--------------------------------------------------------------
| 1 | 534988 | A |
--------------------------------------------------------------
| 2 | 31290 | B |
--------------------------------------------------------------
| 3 | 98765 | C |
--------------------------------------------------------------
| ... | ... | ... |
--------------------------------------------------------------
提前感谢您抽出宝贵时间
【问题讨论】:
-
在视图上,您必须在渲染函数中将上下文作为 dict 发送。在 aboe 示例中,您没有这样做。这就是为什么您无法在模板
render(request,self.template_name, context={'header':header,'rows':rows})上获取变量值的原因
标签: django python-3.x html-table django-templates