From f478b0675caff8fccd44c56694c0f3d43c96e6b8 Mon Sep 17 00:00:00 2001 From: Thomas Vantuycom Date: Wed, 21 Mar 2018 23:42:33 +0100 Subject: [PATCH] Add "forceescape" filter Closes #782. --- CHANGELOG.md | 1 + docs/templating.md | 4 ++++ nunjucks/src/filters.js | 7 +++++++ tests/filters.js | 6 ++++++ 4 files changed, 18 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c65d53b7..11999e48 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ Changelog ========= +* Add `forceescape` filter. Fixes [#782](https://github.com/mozilla/nunjucks/issues/782) 3.1.2 (Feb 23 2018) ------------------- diff --git a/docs/templating.md b/docs/templating.md index 85629e35..bdbc212e 100644 --- a/docs/templating.md +++ b/docs/templating.md @@ -1124,6 +1124,10 @@ This default can be overridden by using the first parameter. 3.5 ``` +### forceescape + +Enforce HTML escaping. This will probably double escape variables. + ### groupby Group a sequence of objects by a common attribute: diff --git a/nunjucks/src/filters.js b/nunjucks/src/filters.js index 5c569005..84bffa04 100644 --- a/nunjucks/src/filters.js +++ b/nunjucks/src/filters.js @@ -156,6 +156,13 @@ function first(arr) { exports.first = first; +function forceescape(str) { + str = (str === null || str === undefined) ? '' : str; + return r.markSafe(lib.escape(str.toString())); +} + +exports.forceescape = forceescape; + function groupby(arr, attr) { return lib.groupBy(arr, attr); } diff --git a/tests/filters.js b/tests/filters.js index 6e6e8483..00e7d3c9 100644 --- a/tests/filters.js +++ b/tests/filters.js @@ -228,6 +228,12 @@ equal('{{ "0" | float }}', '0'); }); + it('forceescape', function(done) { + equal('{{ str | forceescape }}', { str: r.markSafe('')}, '<html>'); + equal('{{ "" | safe | forceescape }}', '<html>'); + finish(done); + }); + it('int', function() { equal('{{ "3.5" | int }}', '3'); equal('{{ "0" | int }}', '0');