Django 模板操作与 if、with、for 和 math-add 用法



我正在尝试在 django 模板中形成一个表。一行将是白色的,另一行将是灰色的...它会像那样继续下去。因此,表格行将显示1个白行,1个灰色行。所以它会更具可读性。我试图设置一个整数变量来决定行在哪个 if 条件下是什么颜色。颜色在class="tr1"和class="tr2"css类中确定。但它总是设置 class="tr1"。所以如果条件有效,总是第一个。解决不了。

{% with 0 as num %}
{% for note in notes %}  
{% if num == 0 %}
<tr class="tr1">
<td class="td_size1">{{note.teacher__name}}</td>
<td class="td_size1">{{note.attendance}}</td>
<td class="td_size1">{{note.time}}</td>
<td class="td_size1">{{note.dailynote}}</td>
</tr>
{{ num|add:1 }}
{% endif %}

{% if num == 1 %}
<tr class="tr2">
<td class="td_size1">{{note.teacher__name}}</td>
<td class="td_size1">{{note.attendance}}</td>
<td class="td_size1">{{note.time}}</td>
<td class="td_size1">{{note.dailynote}}</td>
</tr>
{{ num|add:-1 }}
{% endif %}
{% endfor %}
{% endwith %}

我通过使用css解决了这个问题。 还有一个javascript解决方案,但如果javascript被禁用,它就不起作用。在css中,它检查,它是奇数还是偶数。如果它是奇数,它给出第一个颜色,如果是偶数,它给出第二种颜色。

table.custom1 {
font-family: arial, sans-serif !IMPORTANT;
border-collapse: collapse !IMPORTANT;
width: 100% !IMPORTANT;
}
td.custom1, th.custom1 {
border: 1px solid #511327 !IMPORTANT;
text-align: left !IMPORTANT;
padding: 4px !IMPORTANT;
}
tr.custom1:nth-child(even) {
background-color: #701b36 !IMPORTANT;
}
tr.custom1:nth-child(odd) {
background-color: #5e172e !IMPORTANT;

最新更新