10

I'm trying to build a blog app and the problem is when I use tag 'truncatewords_html' in my template to truncate posts longer than specified number of words, I need to link to complete post by some title like 'read more...' after truncation. So I should know that the post was truncated or not.

P.S.: Is this a pythonic way to solve the problem?

{% 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 %}
Dr. Younes Henni
  • 1,613
  • 1
  • 18
  • 22
sadegh
  • 103
  • 5

4 Answers4

7

This is pretty convoluted but django has some weird corners. Basically I figure if the string length is the same if you truncate at x and x+1 words then the string has not been truncated...

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

You could write a custom template tag (see django docs), or manually check in the template, whether the content you want to display exceeds the given length via length builtin filter.

miku
  • 181,842
  • 47
  • 306
  • 310
1

It comes down to personal preference, but for my taste you're doing way too much work in the template. I would create a method on the Post model, read_more_needed() perhaps, which returns True or False depending on the length of the text. eg:

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)

Then your template would read:

{% if post.read_more_needed %}
  {{ post.body|truncatewords_html:30|safe }}<a href="{{ post.url}}">read more</a>
{% else %}
  {{ post.body|safe }}
{% endif %}
thepeer
  • 8,190
  • 2
  • 18
  • 13
  • If you're going to add "read_more_need()" to the model, then you should be doing the truncation in the model also. The same code doing the truncation should determine if the content has been truncated. – Bryce Feb 29 '12 at 16:41
0

Check out http://code.djangoproject.com/ticket/6799

This patch provides a method to replace the default elipses for truncated text.

Mayuresh
  • 1,062
  • 9
  • 10