Problem

I have a text that I present in a Flask application. The text can contain URLs, and I would like to linkify them, i.e. make them clickable links. Example:

before:

visit http://google.com for...

after:

visit <a href="http://google.com">http://google.com</a> for...

Solution

Before rolling out an own solution, it’s a good idea to check if there is a package for this problem. There is :), and it’s called bleach. Its usage couldn’t be simpler:

>>> import bleach >>> bleach.linkify('an http://example.com url') u'an <a href="http://example.com" rel="nofollow">http://example.com</a> url

Flask integration

In your main file (that calls app.run() ) add the following filter:

import bleach @app.template_filter('linkify') def linkify(s): return bleach.linkify(s)

Then use it in your jinja2 templates:

Description: {{ entry.description|linkify|safe }}

Warning! Apply the “safe” filter only if you trust the origin of the text you want to present in a linkified format.