Login

Template tag to render collections.Counter as an html table

Author:
asfaltboy
Posted:
June 19, 2015
Language:
Python
Version:
1.7
Score:
1 (after 1 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.