1
- ================================
2
- Rendering the table in templates
3
- ================================
4
-
1
+ ===================
2
+ Rendering the table
3
+ ===================
5
4
6
5
A table instance bound to data has two attributes ``columns `` and ``rows ``,
7
6
which can be iterate over:
@@ -27,11 +26,55 @@ For the attributes available on a bound column, see :doc:`features/index`,
27
26
depending on what you want to accomplish.
28
27
29
28
29
+ Custom render methods
30
+ ---------------------
31
+
32
+ Often, displaying a raw value of a table cell is not good enough. For
33
+ example, if your table has a ``rating `` column, you might want to show
34
+ an image showing the given number of **stars **, rather than the plain
35
+ numeric value.
36
+
37
+ While you can always write your templates so that the column in question
38
+ is treated separately, either by conditionally checking for a column name,
39
+ or by explicitely rendering each column manually (as opposed to simply
40
+ looping over the ``rows `` and ``columns `` attributes), this is often
41
+ tedious to do.
42
+
43
+ Instead, you can opt to move certain formatting responsibilites into
44
+ your Python code:
45
+
46
+ .. code-block :: django
47
+
48
+ class BookTable(tables.ModelTable):
49
+ name = tables.Column()
50
+ rating_int = tables.Column(name="rating")
51
+
52
+ def render_rating(self, instance):
53
+ if instance.rating_count == 0:
54
+ return '<img ="no-rating.png">'
55
+ else:
56
+ return '<img ="rating-%s.png">' % instance.rating_int
57
+
58
+ When accessing ``table.rows[i].rating ``, the ``render_rating `` method
59
+ will be called. Note the following:
60
+
61
+ - What is passed is underlying raw data object, in this case, the
62
+ model instance. This gives you access to data values that may not
63
+ have been defined as a column.
64
+ - For the method name, the public name of the column must be used, not
65
+ the internal field name. That is, it's ``render_rating ``, not
66
+ ``render_rating_int ``.
67
+ - The method is called whenever the cell value is retrieved by you,
68
+ whether from Python code or within templates. However, operations by
69
+ ``django-tables ``, like sorting, always work with the raw data.
70
+
71
+
30
72
The table.columns container
31
73
---------------------------
32
74
33
- While you can iterate through ``columns `` and get all the currently visible
34
- columns, it further provides features that go beyond a simple iterator.
75
+ While you can iterate through the ``columns `` attribute and get all the
76
+ currently visible columns, it further provides features that go beyond
77
+ a simple iterator.
35
78
36
79
You can access all columns, regardless of their visibility, through
37
80
``columns.all ``.
0 commit comments