Created
December 8, 2023 15:23
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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