- Author:
- davidblewett
- Posted:
- May 24, 2007
- Language:
- Python
- Version:
- .96
- Score:
- 1 (after 1 ratings)
{% tablify questions name response 8 %}
Will generate a table structure of a list, ensuring that a set number of columns is not exceeded.
It takes 4 arguments: Context Variable Cell Header Attribute Cell Data Attribute Max Number of Columns
The code will loop through the given variable, creating th and td elements for each item. It will create a new tr when the max number of columns is exceeded.
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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | 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) + '<tr>')
lvl = 2
for i in range(self.max_cols):
html.append('%s<th scope="col" align="center">%s</th>' %
(('\t'*lvl), str(getattr(self.var[i], self.header_attr))))
lvl = 1
html.append(('\t'*lvl) + '</tr>')
html.append(('\t'*lvl) + '<tr>')
lvl = 2
for i in range(self.max_cols):
html.append('%s<td align="center" >%s</td>' %
(('\t'*lvl), str(getattr(self.var[0], self.cell_attr))))
self.var.pop(0)
lvl = 1
html.append(('\t'*lvl) + '</tr>')
remaining = len(self.var)
else:
lvl = 2
for i in self.var:
html.append('%s<th scope="col" align="center">%s</th>' %
(('\t'*lvl), str(getattr(i, self.header_attr))))
lvl = 1
html.append(('\t'*lvl) + '</tr>')
html.append(('\t'*lvl) + '<tr>')
lvl = 2
for i in self.var:
html.append('%s<td align="center">%s</td>' %
(('\t'*lvl), str(getattr(i, self.cell_attr))))
lvl = 1
html.append(('\t'*lvl) + '</tr>')
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)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 8 months ago
Comments
Please login first before commenting.