Render a given instance of collections.Counter into a 2 column html table.
Optionally accepts column_title
keyword argument which sets the table
key column header.
Usage:
{% counter_table event_counter column_title='event type' %}
The above will render the a table from the event_counter
variable with the first (key) column set to "event type".
See below for an example template (i.e counter_table.html
)
{% load i18n %}
<table>
<thead>
<tr>
<th>{{column_title|capfirst}}</th>
<th>{% trans "count"|capfirst %}</th>
</tr>
</thead>
<tbody>
{% for key, count in most_common %}
<tr>
<td>{{key}}</td>
<td>{{count}}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<td>{% trans "total"|capfirst %}</td>
<td>{{total_count}}</td>
</tr>
</tfoot>
</table>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | from collections import Counter
from django import template
register = template.Library()
@register.inclusion_tag('counter_table.html')
def counter_table(counter, column_title=None):
"""
Render a given instance of collections.Counter into a 2 column html table.
Optionally accepts `column_title` keyword argument which sets the table
key column header.
Usage:
{% counter_table event_counter column_title='event type' %}
The above will render the a table from the `event_counter` variable
with the first (key) column set to "event type".
"""
assert isinstance(counter, Counter), (
"first argument to counter_table must be an instance "
"of collections.Counter"
)
return dict(most_common=counter.most_common(),
total_count=len(list(counter.elements())),
column_title=column_title)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.