Last Updated: January 08, 2018
· abulte

Urlencode filter in Jinja2

Jinja2 lacks a classic urlencode built-in filter ( Here is a simple one:

import urllib
from markupsafe import Markup

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 }}

1 Response
Add your response

In Python 3 you need to use urllib.parse.quote_plus instead of urllib.quote_plus.

over 1 year ago ·