From 1692a8e63c1666449a9bb51933da837c6d7fcb72 Mon Sep 17 00:00:00 2001 From: Allan Jardine Date: Fri, 18 Dec 2015 12:30:53 +0000 Subject: [PATCH] Fix - renderer: Improvements for the ellipsis helper - Support escaping HTML now - HTML escapes the attibute - Easier to read logic --- dataRender/ellipsis.js | 56 ++++++++++++++++++++++++++---------------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/dataRender/ellipsis.js b/dataRender/ellipsis.js index 117b834..110073f 100644 --- a/dataRender/ellipsis.js +++ b/dataRender/ellipsis.js @@ -9,7 +9,7 @@ * This function should be used with the `dt-init columns.render` configuration * option of DataTables. * - * It accepts two parameters: + * It accepts three parameters: * * 1. `-type integer` - The number of characters to restrict the displayed data * to. @@ -17,6 +17,8 @@ * 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 * expense of showing less characters. + * 2. `-type boolean` (optional - default `false`) - Escape HTML entities + * (`true`) or not (`false` - default). * * @name ellipsis * @summary Restrict output data to a particular length, showing anything @@ -45,31 +47,43 @@ * } ); */ -jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak ) { - return { - display: function ( d ) { - if ( wordbreak === undefined ) { - wordbreak = false; - } +jQuery.fn.dataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) { + var esc = function ( t ) { + return t + .replace( /&/, '&' ) + .replace( //, '>' ) + .replace( /"/, '"' ); + }; - if ( typeof d !== 'number' && typeof d !== 'string' ) { - return d; - } + return function ( d, type, row ) { + // 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 ) { - return d; - } + d = d.toString(); // cast numbers - str = d.substr(0, cutoff); + if ( d.length < cutoff ) { + return d; + } - if ( wordbreak ) { - // Find the last white space character in the string - str = str.replace(/\s([^\s]*)$/, ''); - } + var shortened = d.substr(0, cutoff-1); - return ''+str+'…'; + // 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 ''+shortened+'…'; }; -}; \ No newline at end of file +};