初学者,写的不好,大神见谅!
啥也不说了,直接上了!就是简易着来
urls.py
urlpatterns = [
path('index01/', views.index01, name='index01'), # 就随便写的一个看懂就行映射个测试用的index01
]
views.py
def index01(request): # 为了测试就随乱写的一个例表,模拟多条数据而已, 主要是根据(值value)判断
context = {
'name': [
{
'name': '马队长',
'year': '2020',
'man': 'True',
'title': '自我修养',
},
{
'name': '严队长',
'year': '2021',
'man': 'False',
'title': '小小',
},
{
'name': '六队长',
'year': '2021',
'man': 'False',
'title': '小小',
},
{
'name': '仁队长',
'year': '2021',
'man': 'True',
'title': '小小',
},
{
'name': '好队长',
'year': '2021',
'man': 'True',
'title': '小小',
},
]
}
return render(request, 'text01/index01.html', context=context)
index01.html
<body>
<table border="2" cellspacing="0" width="20%">
<tr>
<th>编号</th>
<th>名称</th>
<th>年份</th>
<th>男人</th>
<th>标题</th>
</tr>
{% for foo in name %} <!-- 这里就是遍历循环开始 -->
<!-- 这里就是if判断开始,我做的是多条件嵌套if判断,如果无需可以把第二层if删除 -->
{% if foo.man == 'True' %} <!-- if判断 “如果男人为真” -->
{% if forloop.counter|divisibleby:2 %} <!-- if判断 “如果男人为真/且序号能被2整除” -->
<tr style="background-color: orange"> <!-- 满足以上两个条件改tr背影色为,orange -->
{% else %} <!-- 另外,不满足序号能被2整除 -->
<tr style="background-color: red"> <!-- 满足男人为真一个条件改tr背影色为,red-->
{% endif %} <!-- 判断整除部分结束-->
{% else %} <!-- 另外就是男人不为真-->
<tr style="background-color: green"> <!-- 改tr背影色为,green-->
{% endif %} <!-- 条件判断全部结整-->
<!-- 以下为for遍历出的内容-->
<td>{{forloop.counter}}</td> <!-- 遍历出所有序号,案例中判断条件-->
<td>{{foo.name}}</td> <!-- 遍历出名字-->
<td>{{foo.year}}</td> <!-- 遍历出年份-->
<td>{{foo.man}}</td> <!-- 遍历出是否为男人,案例中判断条件-->
<td>{{foo.title}}</td> <!-- 遍历出标题-->
</tr>
{% endfor %} <!-- 遍历循环结束-->
</table>
</body>
运行结果如果下:
隔行显示不同的颜色
把index01.html中的12\18\19\20 删除或注释掉就可以了,只留判断是否被2整除
代码如下和上面一样少了几行而已
<body>
<table border="2" cellspacing="0" width="20%">
<tr>
<th>编号</th>
<th>名称</th>
<th>年份</th>
<th>男人</th>
<th>标题</th>
</tr>
{% for foo in name %}
{% if forloop.counter|divisibleby:2 %}
<tr style="background-color: orange">
{% else %}
<tr style="background-color: red">
{% endif %}
<td>{{forloop.counter}}</td>
<td>{{foo.name}}</td>
<td>{{foo.year}}</td>
<td>{{foo.man}}</td>
<td>{{foo.title}}</td>
</tr>
{% endfor %}
</table>
</body>
运行效果如下:
写完了!加了一堆注释有点乱忘见谅!