from django import template
register = template.Library()
class TableNode(template.Node):
def __init__(self, var, header_attr, cell_attr, max_cols):
self.var = var
self.header_attr = header_attr
self.cell_attr = cell_attr
self.max_cols = int(max_cols)
def render(self, context):
self.var = context[self.var][:]
remaining = len(self.var)
html = []
lvl = 2
while remaining >= self.max_cols:
html.append(('\t'*lvl) + '
')
lvl = 2
for i in range(self.max_cols):
html.append('%s%s | ' %
(('\t'*lvl), str(getattr(self.var[i], self.header_attr))))
lvl = 1
html.append(('\t'*lvl) + '
')
html.append(('\t'*lvl) + '')
lvl = 2
for i in range(self.max_cols):
html.append('%s%s | ' %
(('\t'*lvl), str(getattr(self.var[0], self.cell_attr))))
self.var.pop(0)
lvl = 1
html.append(('\t'*lvl) + '
')
remaining = len(self.var)
else:
lvl = 2
for i in self.var:
html.append('%s%s | ' %
(('\t'*lvl), str(getattr(i, self.header_attr))))
lvl = 1
html.append(('\t'*lvl) + '')
html.append(('\t'*lvl) + '')
lvl = 2
for i in self.var:
html.append('%s%s | ' %
(('\t'*lvl), str(getattr(i, self.cell_attr))))
lvl = 1
html.append(('\t'*lvl) + '
')
return ('\n' + ('\t'*lvl)).join(html)
@register.tag(name='tablify')
def get_table(parser, token):
try:
# split_contents() knows not to split quoted strings.
tag_name, var, header_attr, cell_attr, max_cols = token.split_contents()
except ValueError:
raise template.TemplateSyntaxError("%r tag requires 4 arguments " % token.contents[0])
return TableNode(var, header_attr, cell_attr, max_cols)