2013-08-27 52 views
2

在views.py中,我從特定用戶檢索Tweets,然後顯示在模板中,該模板可以工作。在檢索到的推文中使鏈接可點擊

但是,它只是原始文本,即鏈接不可點擊,問題是讓它們可點擊的最佳方式是什麼?

注1:我所指的鏈路可以是任何聯繫,但最有可能的Instagram鏈接

注2:如果可能的話我甚至會想#標籤是點擊。

在views.py代碼

user = twitter.User 
    tweets = [] 
    statuses = t.GetUserTimeline(user) 

    for s in statuses: 
     tweets.append(s.text) 

HTML:

<div class="col2"> 
    <ol class="ol_list"> 
     <h4>Twitter</h4> 
     {% for tweet in tweets %} 
     <li> 
      <p>{{tweet}}</p> 
     </li> 
     {% endfor %} 
    </ol> 
</div> 
+0

有HTML中s.text?還是僅僅是文字? –

+0

@RobL:只是原始文本... – holyredbeard

回答

2

我用這樣的代碼做同樣的事情:

def linkify(raw_message): 
    message = raw_message 
    for url in url_regex.findall(raw_message): 
     if url.endswith('.'): 
      url = url[:-1] 
     if 'http://' not in url: 
      href = 'http://' + url 
     else: 
      href = url 
     message = message.replace(url, '<a href="%s">%s</a>' % (href, url)) 

    return message 

和URL的正則表達式是

url_re = re.compile(r""" 
     [^\s]    # not whitespace 
     [a-zA-Z0-9:/\-]+ # the protocol and domain name 
     \.(?!\.)   # A literal '.' not followed by another 
     [\w\-\./\?=&%~#]+ # country and path components 
     [^\s]    # not whitespace""", re.VERBOSE) 

這正則表達式更喜歡誤報錯誤的索姆邊緣病例。它也匹配尾隨.。不過,我稍後再刪除它。哈希標籤將需要另一個正則表達式來匹配它們。

喜歡的東西:

hashtag_re = re.compile(r""" 
     \#    # a hashmark 
     [^\s]*   # not whitespace repeated""", re.VERBOSE) 
+0

作爲魅力工作,謝謝! – holyredbeard

1

你是不是在你的問題哪一個環節你指的是很清楚的。

如果鏈接的鳴叫內,如鳴叫是:

You should go to this site: example.com

那麼你很可能希望使用正則表達式來識別鏈接,然後拼接HTML到之前的鳴叫本身被傳遞給你的模板。

談到這一點:You should go to this site: example.com

進入這個:You should go to this site: <a href="http://www.example.com">example.com</a>

哈希標籤可以以同樣的方式進行。

談到這一點:Just walked down the street. #yolo

進入這個:Just walked down the street. <a href="https://twitter.com/search?q=%23yolo&src=hash">#yolo</a>