2009-11-26 42 views
7

我正在嘗試構建一個博客應用程序,問題是當我在我的模板中使用標記'truncatewords_html'來縮短比指定數量的文章長的帖子時,我需要通過一些標題鏈接來完成文章,例如「閱讀更多內容」。 ..'截斷後。所以我應該知道該帖子是否被截斷。如何查找內容被截斷?

P.S .:這是解決問題的pythonic方法嗎?

{% ifequal post.body|length post.body|truncatewords_html:max_words|length %} 
    {{ post.body|safe }} 
{% else %} 
    {{ post.body|truncatewords_html:max_words|safe }}<a href="{{ post.url}}">read more</a> 
{% endifequal %} 

回答

4

這很漂亮,但Django有一些奇怪的角落。基本上,我想如果字符串長度是一樣的,如果你削去在x和x + 1點的話則該字符串還沒有被截斷......

{% ifnotequal post.body|truncatewords_html:30|length post.body|truncatewords_html:31|length %} 
    <a href="#">read more...</a> 
{% endifnotequal %} 
2

你可以寫一個自定義模板標籤(見django docs),或手動檢查模板,你要顯示的內容是否通過length內置濾波器長度超過規定長度。

+1

+1檢查顯示器是否超過長度的簡單方法。簡單,工作正常。 –

1

歸結爲個人喜好,但對於我的品味,您在模板中做了太多工作。我會在Post模型上創建一個方法,read_more_needed()也許,它根據文本的長度返回True或False。例如:

def read_more_needed(self): 
    from django.utils.text import truncate_html_words 
    return not truncate_html_words(self.body,30)==truncate_html_words(self.body,31) 

然後你的模板將是:

{% if post.read_more_needed %} 
    {{ post.body|truncatewords_html:30|safe }}<a href="{{ post.url}}">read more</a> 
{% else %} 
    {{ post.body|safe }} 
{% endif %} 
+0

如果您要將「read_more_need()」添加到模型中,那麼您應該也在模型中進行截斷。執行截斷的相同代碼應確定內容是否已被截斷。 – Bryce