Login

Template tag to render collections.Counter as an html table

Author:
asfaltboy
Posted:
June 19, 2015
Language:
Python
Version:
1.7
Tags:
html table inclusion-tag collections.Counter Counter
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

Comments

Please login first before commenting.