在Django应用程序中,我有几个具有相似结构的html页面。我已经为我的所有项目使用了base_site.html模板,但是对于其他页面,我想使用第二个模板来创建表。这些表可能比其他表具有更多或更少的行和列。
我的想法是views.py
中的函数将发送任何给定页面的标题列表以及用于填充表的数据字典,然后在html页面中,我将迭代标题列表以放置表中的标头,然后我将遍历字典以用数据填充表。
在调用table-template.html
的每个函数中,如何拥有headers
来使用变量views.py
?
类似table-template.html
<h1>TEST</h1>
<table>
<tr bgcolor="#ccc">
<th>{% for h in headers %} {{ h }} {% endfor %}</th>
</tr>
</table>
考虑到views.py
中的每个函数都将返回其自己的headers
列表
那我该如何在任何html页面中使用它
{% extends "admin/base_site.html" %}
{% load static %}
{% block content %}
{% include "table-template.html" %}
{% load static %}
{% for key,value in mydict.items %}
<table>
<tr>
<td>{{ value }}</td>
</tr>
</table>
{% endfor %}
答案 0 :(得分:1)
由于您希望标记中的每个值,因此table-template.html可能会稍作更改
<h1>TEST</h1>
<table>
<tr bgcolor="#ccc">
{% for h in headers %}
<th> {{ h }} </th>
{% endfor %}
</tr>
</table>
这将为您创建正确的表头。您可以从上下文字典中的view render方法发送标题列表。
如果未提供您所要查找的完整答案,请随时发表评论。
答案 1 :(得分:0)
通过创建一个继承我的base_site.html
的模板,我实际上设法找到了解决方案,而在所有其他模板上,我将继承我的new_template.html
。因此,这有点像父模板的继承。
我只是在模板中包含了我想要的所有变量(它们在views.py
中的所有函数中均被同名),并且当模板在新页面中扩展时,它从{中的各个函数获取变量的值。 {1}}。