This hopefully is a pretty easy question. My endgoal is to be able to view my database entries in a table which I can sort via the column headers. I have read the documentation on cycle tags, but don't know they mean by 'row1'
and 'row2'
:
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
...
</tr>
{% endfor %}
Secondly, how would I correctly implement it into my template? I am using a very simple JS library, which will allow the sorting:
page.html
{% if Variable %}
<table class="sortable">
<tr>
<th>Title 1</th>
<th>Title 2</th>
<th>Title 3</th>
<th>Title 4</th>
<th>Title 5</th>
</tr>
{% for stuff in Variable %}
<tr class="{% cycle 'stuff' %}">
<td>
<a href="{% url 'detail_page' stuff.id %}">
{{ stuff.Name|capfirst }}</a>
</td>
</tr>
{% endfor %}
</table>
{% else %}
<p>No Results Found</p>
{% endif %}
my models.py in case you need it:
def view(request):
Variable = database.objects.all()
context = {
'Variable': Variable,
}
return render(request, 'app/page.html', context)
EDIT: It seems I had the right code all along, just some unevenly applied CSS that made my table not look like a table. The cycle tag was not needed, only the for loop. It also looked better after adding another table row:
{% for stuff in Variable %}
<tr>
<td>{{ stuff.Name|capfirst }}</td>
<td>{{ stuff.Number|capfirst }}</td>
</tr>
{% endfor %}
For the cycle tag, the two arguments will be added alternately to the template, for example, the code in your template {% for o in some_list %}<tr class="{% cycle 'row1' 'row2' %}"></tr>{% endfor %}
would generate:
<tr class="row1">
...
</tr>
<tr class="row2">
...
</tr>
<tr class="row1">
...
</tr>
<tr class="row2">
...
</tr>
<!-- ... and so on while there are elements in some_list -->
And so on. Normally you would attach some css to this, for example:
<style>
.row1 {
background: #345678;
}
.row2 {
background: #123456;
}
</style>
This would give alternate rows different background colours, for example.