This snippet is a template filter based on "truncate letters" only it will either truncate or pad a string to ensure the output is always a set width.
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 28 | @register.filter
def fixedwidth(value, arg):
"""
Truncates or pads a string to be a certain length
Argument: Desired length of string
"""
try:
length = int(arg)
except ValueError: # invalid literal for int()
return value # Fail silently
if not isinstance(value, basestring):
value = str(value)
if len(value) > (length):
truncated = value[:length - 3]
if not truncated.endswith('...'):
truncated += '...'
return truncated
if len(value) <= length:
padded = value
spaces_needed = (length - len(value)) + 1
for space_needed in range(1, spaces_needed):
padded = "%s " % padded
return padded
return value
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
is probably only ment for non-html output (or output styled like 'white-space: pre'). if used outside that context, don't forget to replace " " with "
" (and maybe "..." with "…
" if you're a typography nerd)nothing wrong with that, just looks complicated.
#
Please login first before commenting.