Urlencode filter in Jinja2
Jinja2 lacks a classic urlencode
built-in filter (http://jinja.pocoo.org/docs/templates/#builtin-filters). Here is a simple one:
import urllib
from markupsafe import Markup
@app.template_filter('urlencode')
def urlencode_filter(s):
if type(s) == 'Markup':
s = s.unescape()
s = s.encode('utf8')
s = urllib.quote_plus(s)
return Markup(s)
Then use it in your Jinja2 template:
{{ variable_to_encode | urlencode }}
Written by Alexandre Bulté
Related protips
1 Response
In Python 3 you need to use urllib.parse.quote_plus
instead of urllib.quote_plus
.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Python
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#