Skip to content

Instantly share code, notes, and snippets.

@archatas
Created February 15, 2026 06:28
Show Gist options
  • Select an option

  • Save archatas/37465cd79d4224736e3f3612be992d96 to your computer and use it in GitHub Desktop.

Select an option

Save archatas/37465cd79d4224736e3f3612be992d96 to your computer and use it in GitHub Desktop.
A template filter for having more control over whitespace characters of text output
{% load text_formatting %}
{% filter normalize_text %}
Hi {{ user.name }},
{% if order.is_urgent %}
⚠️ URGENT: Your order requires immediate attention!\n\n
{% endif %}
Your order #{{ order.id }} has been confirmed.\n
Items:\n
{% for item in order.items %}
\t- {{ item.name }} ({{ item.quantity }}x)\n
{% endfor %}
Total: ${{ order.total }}
Best regards,\n
{{ company.name }}
{% endfilter %}
# myproject/apps/core/templatetags/text_formatting.py
import re
from django import template
register = template.Library()
@register.filter(name='normalize_text')
def normalize_text(value):
"""
Normalizes whitespace in text templates while preserving escaped sequences.
Collapses multiple spaces/newlines but converts r"\n", r"\t", r"\r".
"""
# Replace escaped sequences with placeholders
placeholders = {}
escaped_chars = {
r'\n': '\n',
r'\t': '\t',
r'\r': '\r',
}
for i, (escaped, char) in enumerate(escaped_chars.items()):
placeholder = f'\x00ESCAPED{i}\x00'
placeholders[placeholder] = char
value = value.replace(escaped, placeholder)
# Normalize whitespace
# Replace multiple spaces with single space
value = re.sub(r' +', ' ', value)
# Replace multiple newlines with double newline max
value = re.sub(r'\n\n+', '\n\n', value)
# Remove trailing/leading whitespace on each line
value = '\n'.join(line.strip() for line in value.split('\n'))
# Remove empty lines at start and end
value = value.strip()
# Restore escaped sequences
for placeholder, char in placeholders.items():
value = value.replace(placeholder, char)
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment