Datatables Renderers
Renderers
There are occasions when working with tables that the data source for rows in the table do not contain the value that you wish to show directly in the table. You may wish to transform it to a different representation (a time stamp into a human readable format), combine data points (first and last names) or perform some computation on the value (calculating margin from turnover and expense values).
This transformation of the original data into the value that will be shown in the DataTable is called rendering in DataTables' terminology and is performed using the columns.render
option.
Built-in helpers
DataTables has two built in rendering helpers that can be used to easily format data - more can be added using plug-ins (see below):
number
- for formatting numberstext
- to securely display text from a potentially unsafe source (HTML entities are escaped).
The built in rendering helpers can be accessed under the DataTable.render
object (since 1.11) or $.fn.dataTable.render
(which is an alias to the same object). They are functions (allowing options to be passed into them) which should be immediately executed and their result assigned to the columns.render
method. This might sound a little complicated, but it simply means you would use something like the following:
1
2
3
4
|
{ data: 'price' , render: DataTable.render.number( ... ) } |
Number helper
The number
helper provides the ability to easily format, you guessed it, numbers! When dealing with numbers, you may often wish to add formatting such as prefix and postfix characters (currency indicators for example), use a thousands separator and specify a precision for the number. This is all possible with the number
helper.
The helper function takes up to five optional parameters:
- The thousands separator (required)
- Decimal separator (required)
- Floating point precision - 0 for integers, 1 for a single decimal place, etc (optional)
- A prefix string (optional)
- A postfix string (optional).
For example, to display the price
data point from the data structure shown above in the format $19.99
we would use:
1
2
3
4
|
{ data: 'price' , render: DataTable.render.number( ',' , '.' , 2, '$' ) } |
This example doesn't require the thousands separator, but for larger values such as 1000
they would be formatted as $1,000.00
.
Note that if the number
helper encounters a value which is not a valid number (either number
or string
that contains a number) it will return the value after escaping any HTML entities in it (to help protect against potential security attacks).
Text helper
The text
helper will ensure that any potentially dangerous HTML in the source data will not be executed by escaping the HTML entities. This can be useful if the data being loaded may come from a potentially untrusted data source and can help mitigate XSS attacks.
The text
helper doesn't take any parameters making its use simply:
1
2
3
4
|
{ data: 'product' , render: DataTable.render.text() } |