Django template operations with if, with, for and math-add usage

153 views Asked by At

I am trying to form a table in django template. One row will be white, other row will be gray... And it will go on like that. So the table rows will be displayed 1 white row, 1 gray row. So it will be more readable. I tried to set an integer variable to decide in which if condition what color the row will be. The colors are determined in class="tr1" and class="tr2" css classes. But it is always setting class="tr1". So always 1st if condition is working. Couldnt solve it.

{% 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 %}
1

There are 1 answers

0
ivbtar On

I solved this by using css. There is also a javascript solution but it does not work if javascript disabled. In the css it checks , if it is odd or even. If it is odd it gives first color, if it is even it gives second color.

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;