Sure, here are some examples of using `$.fn.dataTable.render.text()` and `$.fn.dataTable.render.number()` in Yajra DataTables:
Using `$.fn.dataTable.render.text()`
To use `$.fn.dataTable.render.text()` to render the contents of a column as plain text (escaping any HTML):
php
return DataTables::eloquent(User::select())
->addColumn('name', function($user) {
return $.fn.dataTable.render.text($user->name);
})
->toJson();
This will ensure that any HTML in the `name` column is properly escaped to prevent XSS attacks.
Using `$.fn.dataTable.render.number()`
To use `$.fn.dataTable.render.number()` to format a numeric column:
php
return DataTables::eloquent(User::select())
->addColumn('salary', function($user) {
return $.fn.dataTable.render.number(',', '.', 2, '$')($user->salary);
})
->toJson();
This will format the `salary` column with thousands separators, decimal places, and a dollar sign prefix.
The `$.fn.dataTable.render.number()` function takes the following parameters:
1. Thousands separator (e.g. `,`)
2. Decimal separator (e.g. `.`)
3. Number of decimal places to show
4. Prefix (e.g. `$`)
You can adjust these parameters as needed to match your desired formatting.
Remember, you can also use the `rawColumns()` and `escapeColumns()` methods to control how HTML is rendered in your DataTables response:
php
return DataTables::eloquent(User::select())
->rawColumns(['name'])
->escapeColumns(['email'])
->toJson();
This will render the `name` column as HTML, while escaping the `email` column to prevent XSS attacks.
Citations:[1] https://datatables3.rssing.com/chan-5199417/all_p1714.html
[2] https://datatables.net/forums/discussion/45886/how-to-use-fn-datatable-render-text-on-a-columns-without-defining-all-columns
[3] https://datatables.net/examples/advanced_init/column_render.html
[4] https://datatables.net/manual/data/renderers
[5] https://datatables.net/examples/basic_init/data_rendering.html