Browse Source

Changed |tojson filter to quote single attributes

pull/766/head
Armin Ronacher 12 years ago
parent
commit
c502dfbbfb
  1. 5
      CHANGES
  2. 19
      flask/json.py
  3. 6
      flask/testsuite/helpers.py

5
CHANGES

@ -8,6 +8,11 @@ Version 0.10.1
Pending bugfix release. Pending bugfix release.
- Fixed an issue where ``|tojson`` was not quoting single quotes which
made the filter not work properly in HTML attributes. Now it's
possible to use that filter in single quoted attributes. This should
make using that filter with angular.js easier.
Version 0.10 Version 0.10
------------ ------------

19
flask/json.py

@ -165,14 +165,29 @@ def htmlsafe_dumps(obj, **kwargs):
also mark the result as safe. Due to how this function escapes certain also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags. characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
.. versionchanged:: 0.10 .. versionchanged:: 0.10
This function's return value is now always safe for HTML usage, even This function's return value is now always safe for HTML usage, even
if outside of script tags or if used in XHTML. if outside of script tags or if used in XHTML. This rule does not
hold true when using this function in HTML attributes that are double
quoted. Always single quote attributes if you use the ``|tojson``
filter. Alternatively use ``|tojson|forceescape``.
""" """
rv = dumps(obj, **kwargs) \ rv = dumps(obj, **kwargs) \
.replace(u'<', u'\\u003c') \ .replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \ .replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') .replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
if not _slash_escape: if not _slash_escape:
rv = rv.replace('\\/', '/') rv = rv.replace('\\/', '/')
return rv return rv

6
flask/testsuite/helpers.py

@ -104,6 +104,12 @@ class JSONTestCase(FlaskTestCase):
self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"') self.assert_equal(rv, '"\\u003c!--\\u003cscript\\u003e"')
rv = render('{{ "&"|tojson }}') rv = render('{{ "&"|tojson }}')
self.assert_equal(rv, '"\\u0026"') self.assert_equal(rv, '"\\u0026"')
rv = render('{{ "\'"|tojson }}')
self.assert_equal(rv, '"\\u0027"')
rv = render("<a ng-data='{{ data|tojson }}'></a>",
data={'x': ["foo", "bar", "baz'"]})
self.assert_equal(rv,
'<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>')
def test_json_customization(self): def test_json_customization(self):
class X(object): class X(object):

Loading…
Cancel
Save