首页 > 解决方案 > 带有 if、with、for 和 math-add 用法的 Django 模板操作

问题描述

我正在尝试在 django 模板中形成一个表格。一排是白色的,另一排是灰色的……它会这样继续下去。因此表格行将显示 1 个白色行,1 个灰色行。所以它会更具可读性。我试图设置一个整数变量来决定在哪个条件下该行将是什么颜色。颜色在 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 %}

标签: python-2.7django-templatesdjango-1.9

解决方案


我通过使用 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;

推荐阅读