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)