Fix - renderer: Improvements for the ellipsis helper

- Support escaping HTML now
 - HTML escapes the attibute
 - Easier to read logic
pull/236/head
Allan Jardine 9 years ago
parent d51fc04b42
commit 1692a8e63c

@ -9,7 +9,7 @@
* This function should be used with the `dt-init columns.render` configuration * This function should be used with the `dt-init columns.render` configuration
* option of DataTables. * option of DataTables.
* *
* It accepts two parameters: * It accepts three parameters:
* *
* 1. `-type integer` - The number of characters to restrict the displayed data * 1. `-type integer` - The number of characters to restrict the displayed data
* to. * to.
@ -17,6 +17,8 @@
* of the string should not occur in the middle of a word (`true`) or if it * of the string should not occur in the middle of a word (`true`) or if it
* can (`false`). This can allow the display of strings to look nicer, at the * can (`false`). This can allow the display of strings to look nicer, at the
* expense of showing less characters. * expense of showing less characters.
* 2. `-type boolean` (optional - default `false`) - Escape HTML entities
* (`true`) or not (`false` - default).
* *
* @name ellipsis * @name ellipsis
* @summary Restrict output data to a particular length, showing anything * @summary Restrict output data to a particular length, showing anything
@ -45,31 +47,43 @@
* } ); * } );
*/ */
jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak ) { jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
return { var esc = function ( t ) {
display: function ( d ) { return t
if ( wordbreak === undefined ) { .replace( /&/, '&' )
wordbreak = false; .replace( /</, '&lt;' )
} .replace( />/, '&gt;' )
.replace( /"/, '&quot;' );
};
if ( typeof d !== 'number' && typeof d !== 'string' ) { return function ( d, type, row ) {
return d; // Order, search and type get the original data
} if ( type !== 'display' ) {
return d;
}
var str = d.toString(); // cast numbers if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
if ( d.length < cutoff ) { d = d.toString(); // cast numbers
return d;
}
str = d.substr(0, cutoff); if ( d.length < cutoff ) {
return d;
}
if ( wordbreak ) { var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
str = str.replace(/\s([^\s]*)$/, '');
}
return '<span class="ellipsis" title="'+d+'">'+str+'&#8230;</span>'; // Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
} }
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'&#8230;</span>';
}; };
}; };
Loading…
Cancel
Save