Search code examples
pythonflaskjinja2

quote_plus URL-encode filter in Jinja2


There is a urlencode filter in Jinja, which can be used with {{ url | urlencode }}, but I'm looking for a "plus" version that replaces spaces with + instead of %20, like urllib.quote_plus(). Is there anything off the shelf or is it a time for a custom filter?


Solution

  • No, Jinja2 does not have a built-in method that functions like quote_plus; you will need to create a custom filter.

    Python

    from flask import Flask
    # for python2 use 'from urllib import quote_plus' instead
    from urllib.parse import quote_plus
    
    app = Flask('my_app')    
    app.jinja_env.filters['quote_plus'] = lambda u: quote_plus(u)
    

    HTML

    <html>
       {% set url = 'http://stackoverflow.com/questions/33450404/quote-plus-urlencode-filter-in-jinja' %}
       {{ url|quote_plus }}
    </html>