Add urlescape to default filters.
authorAaron Swartz <me@aaronsw.com>
Fri, 6 Jan 2012 15:27:36 +0000 (10:27 -0500)
committerAaron Swartz <me@aaronsw.com>
Fri, 6 Jan 2012 15:27:36 +0000 (10:27 -0500)
jinja2/filters.py
jinja2/testsuite/filters.py

index 352b1668574edb7ae3dd2b0d61dae07119f78117..c170f510f2a9fcda735af577b7a34b89706e4154 100644 (file)
@@ -10,6 +10,7 @@
 """
 import re
 import math
+import urllib
 from random import choice
 from operator import itemgetter
 from itertools import imap, groupby
@@ -69,6 +70,9 @@ def do_forceescape(value):
         value = value.__html__()
     return escape(unicode(value))
 
+def do_urlescape(value):
+    """Escape for use in URLs."""
+    return urllib.quote(value.encode('utf8'))
 
 @evalcontextfilter
 def do_replace(eval_ctx, s, old, new, count=None):
@@ -797,5 +801,9 @@ FILTERS = {
     'round':                do_round,
     'groupby':              do_groupby,
     'safe':                 do_mark_safe,
-    'xmlattr':              do_xmlattr
+    'xmlattr':              do_xmlattr,
+    'urlescape':            do_urlescape,
+    'urle':                 do_urlescape,
+    'urlencode':            do_urlescape,
+    'urlquote':             do_urlescape
 }
index 770bdf2e6158e4187c1af1a5ceb73cda4576ec03..a75129974a10ae2d6a32f5f2cb1a825927f6087d 100644 (file)
@@ -366,7 +366,11 @@ class FilterTestCase(JinjaTestCase):
         assert tmpl.render() == '<div>foo</div>'
         tmpl = env.from_string('{{ "<div>foo</div>" }}')
         assert tmpl.render() == '&lt;div&gt;foo&lt;/div&gt;'
-
+    
+    def test_urlescape(self):
+        env = Environment(autoescape=True)
+        tmpl = env.from_string('{{ "Hello, world!"|urle }}')
+        assert tmpl.render() == 'Hello%2C%20world%21'
 
 def suite():
     suite = unittest.TestSuite()