Login

Truncate words by characters

Author:
trodrigues
Posted:
May 19, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This filter truncates words like the original truncate words Django filter, but instead of being based on the number of words, it's based on the number of characters. I found the need for this when building a website where i'd have to show labels on really small text boxes and truncating by words didn't always gave me the best results (and truncating by character is...well...not that elegant).

Usage example: {{var|truncatewords_by_chars:"16 2 4"}}

If string lenght is higher than 16, truncates by 2 words, if lesser, truncates by 4 words.

 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. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.