Pyt*_*Doe 3 django html-table django-templates python-3.x
我正在尝试使用django 模板语言生成动态 html 表,但我还无法做到。
这是有关我的Views.py和table.html的一些信息
视图.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)
Run Code Online (Sandbox Code Playgroud)
(数据是硬编码的,因为我仍在测试。但是它应该根据用户输入进行更改。)
表.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>
Run Code Online (Sandbox Code Playgroud)
我正在尝试生成这样的东西:
--------------------------------------------------------------
| # | chemblID | Preferable Name |
--------------------------------------------------------------
| 1 | 534988 | A |
--------------------------------------------------------------
| 2 | 31290 | B |
--------------------------------------------------------------
| 3 | 98765 | C |
--------------------------------------------------------------
| ... | ... | ... |
--------------------------------------------------------------
Run Code Online (Sandbox Code Playgroud)
预先感谢您抽出时间
您可以使用 get_context_data 方法将上下文发送到模板
Class table(TemplateView):
template_name = 'table.html'
def get_context_data(self, **kwargs):
ctx = super(table, self).get_context_data(**kwargs)
ctx['header'] = ['#', 'chemblID','Preferable Name']
ctx['rows'] = [{'id':1, 'chemblid':534988,'prefName':'A'},
{'id':2, 'chemblid':31290,'prefName':'B'},
{'id':3, 'chemblid':98765,'prefName':'C'}]
return ctx
Run Code Online (Sandbox Code Playgroud)
您可以删除 html 中的额外循环
<table class="table">
<thead>
<tr>
{% for k in header %}
<th>{{k}}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for r in rows %}
<tr>
<td>{{r.id}}</td>
<td>{{r.chemblid}}</td>
<td>{{r.prefName}}</td>
</tr>
{% endfor %}
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14675 次 |
| 最近记录: |