Reputation: 8774
I'm using the twitter API and am displaying a list of tweets. I'd like to link the usernames and hashtags in my app to the approperiate place, but all I have is a string with an @ and # symbol in them.
Is there a way through django templates I can say "if the variable contains a word starting with #, surround it with "?
Or should I use Javascript to do that?
Any approaches would be helpful.
Upvotes: 1
Views: 283
Reputation: 1319
I'm not sure about handling within the template itself without creating your own filter, but can you handle it in the controller using python? In basic form with a regular expression:
import re
user_pattern = re.compile('(\s|^)(@)(\w+)(\s|$)')
tweet = 'Hey @pssdbt, thats not what I wanted!'
tweet = user_pattern.sub('\1<a href="http://www.twitter.com/\3">\2\3</a>\4', tweet)
Which should result in:
'hey <a href="http://www.twitter.com/pssdbt">@pssdbt</a>, thats not what i wanted!'
Same method would apply to hashtags as well. I don't think it'd be too difficult to take care of in javascript either though.
Update / As a custom filter:
According to http://docs.djangoproject.com/en/dev/howto/custom-template-tags/ you would just create a file called something like your_app/templatetags/twittify.py
In that file, add:
from django import template
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re
register = template.Library()
@register.filter(name='twittify')
def twittify(tweet, autoescape=None):
tweet = conditional_escape(tweet)
user_pattern = re.compile('(\s|^)(@)(\w+)(\s|$)')
tweet = user_pattern.sub('\1<a href="http://www.twitter.com/\3">\2\3</a>\4', tweet)
return mark_safe(tweet)
twittify.needs_autoescape = True
Then in your templates, you should be able to use something like this (assuming this is kind of what it looks like):
<ul id="tweets">
{% for tweet in tweets %}
<li>{{ tweet | twittify }}</li>
{% endfor%}
</ul>
I've never played with custom filters before, but hopefully this at least gets you pointed in the right direction.
Upvotes: 5