Truncate words by characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
from django import template

register = template.Library()

@register.filter
def truncatewords_by_chars(value, arg):
  """
  Truncate words based on the number of characters
  based on original truncatewords filter code
  
  Receives a parameter separated by spaces where each field means:
   - limit: number of characters after which the string is truncated
   - lower bound: if char number is higher than limit, truncate by lower bound
   - higher bound: if char number is less than limit, truncate by higher bound
  """
  from django.utils.text import truncate_words
  try:
    args = arg.split(' ')
    limit = int(args[0])
    lower = int(args[1])
    higher = int(args[2])
  except ValueError: # Invalid literal for int().
    return value
  if len(value) >= limit:
    return truncate_words(value, lower)
  if len(value) < limit:
    return truncate_words(value, higher)

More like this

  1. truncatehtml_at_word by zakj 4 years, 6 months ago
  2. Precise truncate chars filter by davmuz 1 year, 4 months ago
  3. Truncate string after a given number of chars keeping whole words by rix 4 years, 4 months ago
  4. Truncate filter by zalun 4 years ago
  5. truncate letters by trbs 6 years, 2 months ago

Comments

(Forgotten your password?)