disruptive
disruptive

Reputation: 5946

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?

Upvotes: 16

Views: 15643

Answers (2)

Marat Zaynutdinoff
Marat Zaynutdinoff

Reputation: 313

FastAPI variant

from fastapi.templating import Jinja2Templates
from urllib.parse import quote_plus

templates = Jinja2Templates(directory="templates")
templates.env.filters['quote_plus'] = lambda x: quote_plus(str(x)) if x else ''

HTML code is same as in @wondercricket 's answer

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

Upvotes: 0

Wondercricket
Wondercricket

Reputation: 7872

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>

Upvotes: 20

Related Questions