I have a Django template where I'm trying to display a list as an unordered list in html. Currently I have it done it in a pretty messy way, using |length
and |slice
:
{% if list_tasks %}
The following tasks will be removed from this group:
<ul>
{% for task in list_tasks|slice:":10" %}
<li>{{ task.name }}</li>
{% endfor %}
{% if list_tasks|length > 10 %}
<li>...and {{ list_tasks|length|add:"-10" }} other tasks</li>
{% endif %}
</ul>
{% endif %}
If list_tasks
has 253 elements, the output is something like this:
The following tasks will be removed from this group:
- T06/081
- T15/0395
- T15/0545
- T11/723
- T13/758
- T14/1532
- T14/1512
- T14/1510
- T04/154
- T14/1528
- ...and 243 other tasks
Is there a neater and cleaner way of doing this?
I'd say your solution isn't all that bad :)
1. But some would probably mention that you would be better off formatting your truncated list in the view if it is anything that requires more than the most basic formatting operations in the template.
It looks like you are displaying that last "...other tasks" line in the same way as the rest of the actual tasks, so that would be the cleanest method.
Something like this in your view, then access truncated_tasks in the template:
truncate_to = 10
truncated_tasks = tasks[:truncate_to]
if len(tasks) > truncate_to:
truncated_tasks.append('...and %s other task(s)' % (len(tasks)-truncate_to))
2. Although, depending on the audience I might prefer to just pushing the entire list to the template and using a js snippet/plugin to hide/show the other entries just in case someone wanted to view/copy-paste the full list :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With