0

I have a post object which has content attribute which is basically a TextField. I want to show first few sentences (not words, I want it to truncate after 2-3 full stops, or something like that) as preview of post on my webpage.

{{ post.content }}

How do I do that in my template?

Victor
  • 3
  • 3
  • Look up Django template tags and filters filters that should do exactly what you want – fkay May 02 '22 at 08:19

1 Answers1

0

First, you need to split the given text into sentences, you can use the function provided in this answer

Next, register your custom template tag that uses the above function, and here you go:

from django import template
from django.template.defaultfilters import stringfilter

from <your utils package> import split_into_sentences

register = template.Library()

@register.filter
@stringfilter
def truncate_sentences(value, length=3):
    sentences = split_into_sentences(value)
    return ' '.join(sentences[:length])

Then simply use the custom template tag in your template:

{{ post.content|truncate_sentences:3 }}
Ersain
  • 1,466
  • 1
  • 9
  • 20