我不确定在没有创建自己的过滤器的情况下在模板内处理,但是你可以使用python在控制器中处理它吗?在带有正则表达式的基本形式中:
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)
Run Code Online (Sandbox Code Playgroud)
哪个应该导致:
'hey <a href="http://www.twitter.com/pssdbt">@pssdbt</a>, thats not what i wanted!'
Run Code Online (Sandbox Code Playgroud)
同样的方法也适用于主题标签.不过,我认为用javascript来处理它并不困难.
更新/作为自定义过滤器:
根据http://docs.djangoproject.com/en/dev/howto/custom-template-tags/,您只需创建一个名为your_app/templatetags/twittify.py的文件.
在该文件中,添加:
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
Run Code Online (Sandbox Code Playgroud)
然后在你的模板中,你应该可以使用这样的东西(假设这是它的样子):
<ul id="tweets">
{% for tweet in tweets %}
<li>{{ tweet | twittify }}</li>
{% endfor%}
</ul>
Run Code Online (Sandbox Code Playgroud)
我以前从未使用过自定义过滤器,但希望这至少会让你指向正确的方向.