How to find that the content is truncated?

后端 未结 4 1254
误落风尘
误落风尘 2021-01-02 05:05

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 li

4条回答
  •  抹茶落季
    2021-01-02 05:29

    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 }}read more
    {% else %}
      {{ post.body|safe }}
    {% endif %}
    

提交回复
热议问题