diff --git a/docs/templating.md b/docs/templating.md index 3bf01343..692cd4d4 100644 --- a/docs/templating.md +++ b/docs/templating.md @@ -784,6 +784,14 @@ true, result will be reversed. Sort is case-insensitive by default, but setting `caseSens` to true makes it case-sensitive. If `attr` is passed, will compare `attr` from each item. +### striptags (value, [preserve_linebreaks]) + +Analog of jinja's [striptags](http://jinja.pocoo.org/docs/templates/#striptags). If `preserve_linebreaks` is false (default), +strips SGML/XML tags and replaces adjacent whitespace with one space. +If `preserve_linebreaks` is true, normalizes whitespace, trying to preserve original +linebreaks. Use second behavior if you want to pipe +`{{ text | striptags | nl2br }}`. Use default one otherwise. + ### More Filters * [abs](http://jinja.pocoo.org/docs/templates/#abs) @@ -809,7 +817,6 @@ passed, will compare `attr` from each item. * [selectattr](http://jinja.pocoo.org/docs/templates/#selectattr) (only the single-argument form) * [slice](http://jinja.pocoo.org/docs/templates/#slice) * [string](http://jinja.pocoo.org/docs/templates/#string) -* [striptags](http://jinja.pocoo.org/docs/templates/#striptags) * [title](http://jinja.pocoo.org/docs/templates/#title) * [trim](http://jinja.pocoo.org/docs/templates/#trim) * [truncate](http://jinja.pocoo.org/docs/templates/#truncate) diff --git a/src/filters.js b/src/filters.js index b95b2b15..10f939d9 100644 --- a/src/filters.js +++ b/src/filters.js @@ -398,10 +398,22 @@ var filters = { return r.copySafeness(obj, obj); }, - striptags: function(input) { + striptags: function(input, preserve_linebreaks) { input = normalize(input, ''); + preserve_linebreaks = preserve_linebreaks || false; var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>|/gi; - return r.copySafeness(input, filters.trim(input.replace(tags, '')).replace(/\s+/gi, ' ')); + var trimmedInput = filters.trim(input.replace(tags, '')); + var res = ''; + if (preserve_linebreaks) { + res = trimmedInput + .replace(/^ +| +$/gm, '') // remove leading and trailing spaces + .replace(/ +/g, ' ') // squash adjacent spaces + .replace(/(\r\n)/g, '\n') // normalize linebreaks (CRLF -> LF) + .replace(/\n\n\n+/g, '\n\n'); // squash abnormal adjacent linebreaks + } else { + res = trimmedInput.replace(/\s+/gi, ' '); + } + return r.copySafeness(input, res); }, title: function(str) { diff --git a/tests/filters.js b/tests/filters.js index 80fd2e47..09d59d63 100644 --- a/tests/filters.js +++ b/tests/filters.js @@ -405,6 +405,12 @@ equal('{{ undefined | striptags }}', ''); equal('{{ null | striptags }}', ''); equal('{{ nothing | striptags }}', ''); + equal('{{ html | striptags(true) }}', + { + html: '