From b65fce659502ac5e211d13fbd5435e1ff6c703d2 Mon Sep 17 00:00:00 2001 From: Jacob Kaplan-Moss Date: Tue, 4 Dec 2007 21:08:29 +0000 Subject: [PATCH] Fixed #4131: added an "escapejs" filter for use in JavaScript strings, and updated the documentation on addslashes to point to the new ticket. Featuring contributions from Ned Batchelder, Jeremy Dunck, and Andy Durdin. git-svn-id: http://code.djangoproject.com/svn/django/trunk@6892 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/template/defaultfilters.py | 25 ++++++++++++++++++- docs/templates.txt | 13 +++++++++- tests/regressiontests/defaultfilters/tests.py | 12 +++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/django/template/defaultfilters.py b/django/template/defaultfilters.py index ac92bef6cf..9514c92d50 100644 --- a/django/template/defaultfilters.py +++ b/django/template/defaultfilters.py @@ -43,7 +43,11 @@ def stringfilter(func): def addslashes(value): - """Adds slashes - useful for passing strings to JavaScript, for example.""" + """ + Adds slashes before quotes. Useful for escaping strings in CSV, for + example. Less useful for escaping JavaScript; use the ``escapejs`` + filter instead. + """ return value.replace('\\', '\\\\').replace('"', '\\"').replace("'", "\\'") addslashes.is_safe = True addslashes = stringfilter(addslashes) @@ -54,6 +58,25 @@ def capfirst(value): capfirst.is_safe=True capfirst = stringfilter(capfirst) +_js_escapes = ( + ('\\', '\\\\'), + ('"', '\\"'), + ("'", "\\'"), + ('\n', '\\n'), + ('\r', '\\r'), + ('\b', '\\b'), + ('\f', '\\f'), + ('\t', '\\t'), + ('\v', '\\v'), + ('>> capfirst(u'hello world') u'Hello world' +>>> escapejs(u'"double quotes" and \'single quotes\'') +u'\\"double quotes\\" and \\\'single quotes\\\'' + +>>> escapejs(ur'\ : backslashes, too') +u'\\\\ : backslashes, too' + +>>> escapejs(u'and lots of whitespace: \r\n\t\v\f\b') +u'and lots of whitespace: \\r\\n\\t\\v\\f\\b' + +>>> escapejs(ur'') +u'