Reputation: 67
I am making a social networking site. I am wondering how to make a jinja filter in python to make any word that starts with @ a link to their profile.
Upvotes: 1
Views: 172
Reputation: 10850
Here's a Jinja filter you can use:
from flask import Markup
def linkify(text):
return Markup(re.sub(r'@([a-zA-Z0-9_]+)', r'<a href="/\1">@\1</a>', text))
It finds usernames starting with @
, containing lowercase or uppercase letters, numbers and underscores. It replaces it a link to the profile (\1
represents their username without the @
)
Here's how you'd add it to you're environment:
app.jinja_env.filters['linkify'] = linkify
And call it from a Jinja template:
{{ post|linkify }}
EDIT
Run this in a Python shell:
>>> import re
>>> text = 'This is a post mentioning @nathancahill and @jacob_bennet'
>>> re.sub(r'@([a-zA-Z0-9_]+)', r'<a href="/\1">@\1</a>', text)
'This is a post mentioning <a href="/nathancahill">@nathancahill</a> and <a href="/jacob_bennet">@jacob_bennet</a>'
Do you get the same output?
Upvotes: 2