Truncate text to length up until the nearest space

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from django import template

register = template.Library()

@register.filter
def truncate_char_to_space(value, arg):
    data = str(value)
    if len(value) < arg:
        return data     
        
    if data.find(' ', arg, arg+5) == -1:
        return data[:arg] + '...'
    else:
        return data[:arg] + data[arg:data.find(' ', arg)] + '...'

More like this

  1. Truncate string after a given number of chars keeping whole words by rix 4 years, 4 months ago
  2. Truncate words by characters by trodrigues 5 years ago
  3. truncatehtml_at_word by zakj 4 years, 6 months ago
  4. Truncate filter by zalun 4 years ago
  5. Effective content caching for mass-load site using redirect feature by nnseva 1 year, 10 months ago

Comments

(Forgotten your password?)