Sachin
Sachin

Reputation: 3782

Blog excerpt in Django

I am building a blog application in Django and when I display all the blogs I want to display a small blog excerpt with each entry. Can anybody tell me how can I do that?

One way to do that would be to make an extra field and store a fixed number of words for each blog entry, let's say 20 words. But then that would be storing redundant information in the database. Is there a better way to do that?

Upvotes: 11

Views: 4367

Answers (3)

codeape
codeape

Reputation: 100766

I suggest you use the truncatewords template filter.

Template example:

<ul>
{% for blogpost in blogposts %}
    <li><b>{{blogpost.title}}</b>: {{blogpost.content|truncatewords:10}}</li>
{% endfor %}
</ul>

If the blog content is stored as HTML, use truncatewords_html to ensure that open tags are closed after the truncation point (or combine with striptags to remove html tags).

If you want to truncate on characters (not words), you can use slice:

{{blogpost.content|slice:":10"}}

(outputs first 10 characters).

If content is stored as HTML, combine with striptags to avoid open tags problems: {{blogpost.content|striptags|slice:":10"}}

Upvotes: 21

robnardo
robnardo

Reputation: 931

Somewhat related..

I just provided an answer to this question: Django strip_tags template filter add space that may help others when making excerpts that contain HTML tags and short content in <p> tags.

Helps convert this..

"<p>This is a paragraph.</p><p>This is another paragraph.</p>"

to this..

'This is a paragraph. This is another paragraph.'

instead of this..

'This is a paragraph.This is another paragraph.'

Upvotes: 1

Holly
Holly

Reputation: 1217

In Django 1.4 and later, there's a truncatechars filter that will truncate a string to a specific length and terminate it with .... It actually truncates it to the specific length minus 3, and the last 3 characters become the ....

Upvotes: 2

Related Questions