Turn an object list into a table with django templatetags

/project/myapp/myapp_admin_tags.py:

from django import template
from django.core.urlresolvers import reverse


register = template.Library()

@register.tag(name="make_table")
def do_make_table(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, object_list, caption, field_list = token.split_contents()
field_list = field_list.replace('\"','')
field_list = field_list.split(",")
caption = caption.replace('\"','')
except ValueError:
raise template.TemplateSyntaxError("%r tag requires exactly three arguments" % token.contents.split()[0])
return MakeTable(object_list,caption, field_list)

class MakeTable(template.Node):
def __init__(self, object_list,caption, field_list):
self.object_list = template.Variable(object_list )
self.field_list = field_list
self.caption = caption

def render(self, context):
try:
caption_html="<caption>%s</caption>" %( self.caption)

object_list = self.object_list.resolve(context)
th_fields = self.field_list

th_html=""
for th in th_fields:
th_html += "<th>%s</th>" %(th.replace("_"," ").capitalize())
thead = "<thead><tr>%s</tr></thead>" %(th_html)

tr_html=""
for obj in object_list:
td_html=""
for field in self.field_list:
if field == th_fields[0]: #is first col in list
url = reverse('admin:%s_%s_change' %(obj._meta.app_label,obj.__class__.__name__.lower()), args=(obj.id,) )
td_html += "<td><a href='%s'>%s</a></td>" %(url,obj.__getattribute__(field.replace("'","")))
else:
td_html += "<td>%s</td>" %(obj.__getattribute__(field.replace("'","")))
tr_html += "<tr>%s</tr>" % (td_html)
table_html = "<table>%s %s %s</table>" %(caption_html, thead, tr_html)

return table_html
except template.VariableDoesNotExist:
return ''

Template:

{% make_table changes "Recent Changes" "updated_on,job,node,performed_command,successful" %}

Where outputs is a list of "Change" objects, "Recent Changes" is what I want the table caption to be, then a list of all the fields I want in the table.

Tagged as django , make_table templatetags
Written by Andrew Konkol on July 20th, 2012

0 Comments

Log in with Twitter, Google, Facebook, LinkedIn to leave a comment.