Tablify templatetag

 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

  1. Group sequence into rows and columns for a TABLE by davidwtbuxton 2 years, 4 months ago
  2. Functional Filters by waterson 5 years, 8 months ago
  3. Python Calendar wrapper template tag by dokterbob 4 years, 1 month ago
  4. Reshape list for table, flatten index in nested loops by aquagnu 5 years, 3 months ago
  5. Showell markup--DRY up your templates by showell 3 years, 6 months ago

Comments

(Forgotten your password?)