From 06a8b1c02b2091b31ef4f39ddde3184f25f58260 Mon Sep 17 00:00:00 2001 From: Aaron Swartz Date: Fri, 6 Jan 2012 10:27:36 -0500 Subject: [PATCH] Add urlescape to default filters. --- jinja2/filters.py | 10 +++++++++- jinja2/testsuite/filters.py | 6 +++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/jinja2/filters.py b/jinja2/filters.py index 352b166..c170f51 100644 --- a/jinja2/filters.py +++ b/jinja2/filters.py @@ -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 } diff --git a/jinja2/testsuite/filters.py b/jinja2/testsuite/filters.py index 770bdf2..a751299 100644 --- a/jinja2/testsuite/filters.py +++ b/jinja2/testsuite/filters.py @@ -366,7 +366,11 @@ class FilterTestCase(JinjaTestCase): assert tmpl.render() == '
foo
' tmpl = env.from_string('{{ "
foo
" }}') assert tmpl.render() == '<div>foo</div>' - + + 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() -- 2.26.2