Login

Generate and render HTML Table

Author:
LLyaudet
Posted:
June 30, 2022
Language:
Python
Version:
3.2
Score:
0 (after 0 ratings)

A set of classes that enables fast and flexible generation of HTML tables from columns definitions and datasets. With classes arguments, it is easy to style it with bootstrap for example.

  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
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
from typing import Optional, Dict, List, Callable

from django.utils.html import escape


class Cell:
    def __init__(
        self,
        value: str,
        is_header: bool = False,
        title: Optional[str] = None,
        classes: Optional[str] = None,
        extra_data: Optional[Dict] = None,
    ):
        self.value = value
        self.is_header = is_header
        self.title = title
        self.classes = classes
        self.extra_data = extra_data

    def render(self) -> str:
        result = ""

        if self.is_header:
            result += "<th"
        else:
            result += "<td"
        title = self.render_title()
        if title is not None:
            result += ' title="' + title + '"'
        classes = self.render_classes()
        if classes is not None:
            result += ' class="' + classes + '"'
        result += ">"

        result += self.render_inner()

        if self.is_header:
            result += "</th>"
        else:
            result += "</td>"
        return result

    def render_inner(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Cell_render_inner") is not None
        ):
            return self.extra_data.get("Cell_render_inner")(
                self.value,
                self.extra_data,
            )
        return escape(str(self.value))

    def render_title(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Cell_render_title") is not None
        ):
            return self.extra_data.get("Cell_render_title")(
                self.value,
                self.title,
                self.extra_data,
            )
        if self.title is None:
            return None
        return escape(str(self.title))

    def render_classes(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Cell_render_classes") is not None
        ):
            return self.extra_data.get("Cell_render_classes")(
                self.value,
                self.classes,
                self.extra_data,
            )
        if self.classes is None:
            return None
        return escape(str(self.classes))



class Row:
    def __init__(
        self,
        cells: List[Cell],
        title: Optional[str] = None,
        classes: Optional[str] = None,
        extra_data: Optional[Dict] = None,
    ):
        self.cells = cells
        self.title = title
        self.classes = classes
        self.extra_data = extra_data

    def render(self) -> str:
        result = "<tr"
        title = self.render_title()
        if title is not None:
            result += ' title="' + title + '"'
        classes = self.render_classes()
        if classes is not None:
            result += ' class="' + classes + '"'
        result += ">"

        result += self.render_inner()

        result += "</tr>"
        return result

    def render_inner(self) -> str:
        result = ""
        for cell in self.cells:
            result += cell.render()
        return result

    def render_title(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Row_render_title") is not None
        ):
            return self.extra_data.get("Row_render_title")(
                self.title,
                self.extra_data,
            )
        if self.title is None:
            return None
        return escape(str(self.title))

    def render_classes(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Row_render_classes") is not None
        ):
            return self.extra_data.get("Row_render_classes")(
                self.classes,
                self.extra_data,
            )
        if self.classes is None:
            return None
        return escape(str(self.classes))



class TableHeadOrBody:
    def __init__(
        self,
        rows: List[Row],
        is_head: bool = False,
        classes: Optional[str] = None,
        extra_data: Optional[Dict] = None,
    ):
        self.rows = rows
        self.is_head = is_head
        self.classes = classes
        self.extra_data = extra_data

    def render(self) -> str:
        result = ""
        if self.is_head:
            result += "<thead"
        else:
            result += "<tbody"
        classes = self.render_classes()
        if classes is not None:
            result += ' class="' + classes + '"'
        result += ">"

        result += self.render_inner()

        if self.is_head:
            result += "</thead>"
        else:
            result += "</tbody>"
        return result

    def render_inner(self) -> str:
        result = ""
        for row in self.rows:
            result += row.render()
        return result

    def render_classes(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("TableHeadOrBody_render_classes") is not None
        ):
            return self.extra_data.get("TableHeadOrBody_render_classes")(
                self.classes,
                self.extra_data,
            )
        if self.classes is None:
            return None
        return escape(str(self.classes))



class Table:
    def __init__(
        self,
        table_head: Optional[TableHeadOrBody],
        table_body: Optional[TableHeadOrBody],
        classes: Optional[str] = None,
        extra_data: Optional[Dict] = None,
    ):
        self.table_head = table_head
        self.table_body = table_body
        self.classes = classes
        self.extra_data = extra_data

    def render(self) -> str:
        result = "<table"
        classes = self.render_classes()
        if classes is not None:
            result += ' class="' + classes + '"'
        result += ">"

        result += self.render_inner()

        result += "</table>"
        return result

    def render_inner(self) -> str:
        result = ""
        if self.table_head is not None:
            result += self.table_head.render()
        if self.table_body is not None:
            result += self.table_body.render()
        return result

    def render_classes(self) -> str:
        if (
            self.extra_data is not None
            and self.extra_data.get("Table_render_classes") is not None
        ):
            return self.extra_data.get("Table_render_classes")(
                self.classes,
                self.extra_data,
            )
        if self.classes is None:
            return None
        return escape(str(self.classes))



class Column:
    def __init__(
        self,
        header_name: str,
        attribute_name: str,
        header_Cell_render_inner: Optional[Callable] = None,
        header_Cell_render_title: Optional[Callable] = None,
        header_Cell_render_classes: Optional[Callable] = None,
        body_Cell_render_inner: Optional[Callable] = None,
        body_Cell_render_title: Optional[Callable] = None,
        body_Cell_render_classes: Optional[Callable] = None,
        header_title: Optional[str] = None,
        header_classes: Optional[str] = None,
        body_title: Optional[str] = None,
        body_classes: Optional[str] = None,
    ):
        self.header_name = header_name
        self.attribute_name = attribute_name
        self.header_Cell_render_inner = header_Cell_render_inner
        self.header_Cell_render_title = header_Cell_render_title
        self.header_Cell_render_classes = header_Cell_render_classes
        self.body_Cell_render_inner = body_Cell_render_inner
        self.body_Cell_render_title = body_Cell_render_title
        self.body_Cell_render_classes = body_Cell_render_classes
        self.header_title = header_title
        self.header_classes = header_classes
        self.body_title = body_title
        self.body_classes = body_classes

    def _get_header_extra_data(self, extra_data: Optional[Dict]) -> Optional[Dict]:
        if self.header_Cell_render_inner is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Cell_render_inner"] = self.header_Cell_render_inner
        if self.header_Cell_render_title is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Cell_render_title"] = self.header_Cell_render_title
        if self.header_Cell_render_classes is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Cell_render_classes"] = self.header_Cell_render_classes
        return extra_data

    def get_header_cell(self, extra_data: Optional[Dict] = None) -> Cell:
        return Cell(
            value=self.header_name,
            is_header=True,
            title=self.header_title,
            classes=self.header_classes,
            extra_data=self._get_header_extra_data(extra_data),
        )

    def _get_body_extra_data(
        self,
        extra_data: Optional[Dict],
        data_or_object,
    ) -> Optional[Dict]:
        if extra_data is None:
            extra_data = {}
        extra_data["row"] = data_or_object
        if self.body_Cell_render_inner is not None:
            extra_data["Cell_render_inner"] = self.body_Cell_render_inner
        if self.body_Cell_render_title is not None:
            extra_data["Cell_render_title"] = self.body_Cell_render_title
        if self.body_Cell_render_classes is not None:
            extra_data["Cell_render_classes"] = self.body_Cell_render_classes
        return extra_data

    def get_body_cell(self, data_or_object, extra_data: Optional[Dict] = None) -> Cell:
        if hasattr(data_or_object, self.attribute_name):
            value = getattr(data_or_object, self.attribute_name)
        else:
            value = data_or_object.get(self.attribute_name)
        return Cell(
            value=value,
            is_header=False,
            title=self.body_title,
            classes=self.body_classes,
            extra_data=self._get_body_extra_data(extra_data, data_or_object),
        )



class TableDefinition:
    def __init__(
        self,
        columns: List[Column],
        data_list: List,
        header_row_title: Optional[str] = None,
        header_row_classes: Optional[str] = None,
        header_Row_render_title: Optional[Callable] = None,
        header_Row_render_classes: Optional[Callable] = None,
        body_row_title: Optional[str] = None,
        body_row_classes: Optional[str] = None,
        body_Row_render_title: Optional[Callable] = None,
        body_Row_render_classes: Optional[Callable] = None,
        header_classes: Optional[str] = None,
        header_TableHeadOrBody_render_classes: Optional[Callable] = None,
        body_classes: Optional[str] = None,
        body_TableHeadOrBody_render_classes: Optional[Callable] = None,
        table_classes: Optional[str] = None,
        Table_render_classes: Optional[Callable] = None,
    ):
        self.columns = columns
        self.data_list = data_list
        self.header_row_title = header_row_title
        self.header_row_classes = header_row_classes
        self.header_Row_render_title = header_Row_render_title
        self.header_Row_render_classes = header_Row_render_classes
        self.body_row_title = body_row_title
        self.body_row_classes = body_row_classes
        self.body_Row_render_title = body_Row_render_title
        self.body_Row_render_classes = body_Row_render_classes
        self.header_classes = header_classes
        self.header_TableHeadOrBody_render_classes = (
            header_TableHeadOrBody_render_classes
        )
        self.body_classes = body_classes
        self.body_TableHeadOrBody_render_classes = body_TableHeadOrBody_render_classes
        self.table_classes = table_classes
        self.Table_render_classes = Table_render_classes

    def _get_header_row_extra_data(self, extra_data: Optional[Dict]) -> Optional[Dict]:
        if self.header_Row_render_title is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Row_render_title"] = self.header_Row_render_title
        if self.header_Row_render_classes is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Row_render_classes"] = self.header_Row_render_classes
        return extra_data

    def _get_table_header_extra_data(
        self,
        extra_data: Optional[Dict],
    ) -> Optional[Dict]:
        if self.header_TableHeadOrBody_render_classes is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["TableHeadOrBody_render_classes"] = (
                self.header_TableHeadOrBody_render_classes
            )
        return extra_data

    def _get_table_head(self) -> TableHeadOrBody:
        header_cells = []
        for column in self.columns:
            header_cells.append(column.get_header_cell())
        header_row = Row(
            header_cells,
            title=self.header_row_title,
            classes=self.header_row_classes,
            extra_data=self._get_header_row_extra_data(None),
        )
        table_head = TableHeadOrBody(
            [header_row],
            is_head=True,
            classes=self.header_classes,
            extra_data=self._get_table_header_extra_data(None),
        )
        return table_head

    def _get_body_row_extra_data(self, extra_data: Optional[Dict]) -> Optional[Dict]:
        if self.body_Row_render_title is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Row_render_title"] = self.body_Row_render_title
        if self.body_Row_render_classes is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["Row_render_classes"] = self.body_Row_render_classes
        return extra_data

    def _get_table_body_extra_data(self, extra_data: Optional[Dict]) -> Optional[Dict]:
        if self.body_TableHeadOrBody_render_classes is not None:
            if extra_data is None:
                extra_data = {}
            extra_data["TableHeadOrBody_render_classes"] = (
                self.body_TableHeadOrBody_render_classes
            )
        return extra_data

    def _get_table_body(self) -> TableHeadOrBody:
        body_rows = []
        for data in self.data_list:
            body_cells = []
            for column in self.columns:
                body_cells.append(column.get_body_cell(data))
            body_row = Row(
                body_cells,
                title=self.body_row_title,
                classes=self.body_row_classes,
                extra_data=self._get_body_row_extra_data(None),
            )
            body_rows.append(body_row)
        table_body = TableHeadOrBody(
            body_rows,
            is_head=False,
            classes=self.body_classes,
            extra_data=self._get_table_body_extra_data(None),
        )
        return table_body

    def _get_table_extra_data(self, extra_data: Optional[Dict]) -> Optional[Dict]:
        if self.Table_render_classes is not None:
            extra_data["Table_render_classes"] = (
                self.Table_render_classes
            )
        return extra_data

    def get_table(self) -> Table:
        table_head = self._get_table_head()
        table_body = self._get_table_body()
        return Table(
            table_head=table_head,
            table_body=table_body,
            classes=self.table_classes,
            extra_data=self._get_table_extra_data({}),
        )

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.