Home > flask, python > Flask: linkify a text

Flask: linkify a text

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:


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


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

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

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.

  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: