Skip to content

Instantly share code, notes, and snippets.

@DArmstrong87
Created December 8, 2023 15:23
Show Gist options
  • Save DArmstrong87/0cd7c7a80e4a25279695e48af253aaca to your computer and use it in GitHub Desktop.
Save DArmstrong87/0cd7c7a80e4a25279695e48af253aaca to your computer and use it in GitHub Desktop.
Custom Django template filter: Confine a string to a max length, replace last three characters with ellipses
from django import template
register = template.Library()
@register.filter(name="truncate_with_ellipses")
def truncate_with_ellipses(value: str, max_length: int) -> str:
"""
Confine a string to a max length, replace last three characters with ellipses
"""
if len(value) <= max_length:
return value
else:
truncated_value = value[: max_length - 3] + "..."
return truncated_value
# Usage in template: {{variable|truncate_with_ellipses:50}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment