Last active
August 11, 2025 03:06
-
-
Save martinsvoboda/1bf965a8c6037c0fe1a88d89ea822df6 to your computer and use it in GitHub Desktop.
Django template custom tag nospace - Removes whitespace inside tags and text
This file contains hidden or 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
import re | |
from django.utils.encoding import force_text | |
from django.template import Library, Node | |
register = Library() | |
def strip_spaces_in_tags(value): | |
value = force_text(value) | |
value = re.sub(r'\s+', ' ', value) | |
value = re.sub(r'>\s+', '>', value) | |
value = re.sub(r'\s+<', '<', value) | |
return value | |
class NoSpacesNode(Node): | |
def __init__(self, nodelist): | |
self.nodelist = nodelist | |
def render(self, context): | |
return strip_spaces_in_tags(self.nodelist.render(context).strip()) | |
@register.tag | |
def nospaces(parser, token): | |
""" | |
Removes any duplicite whitespace in tags and text. Can be used as supplementary tag for {% spaceless %}:: | |
{% nospaces %} | |
<strong> | |
Hello | |
this is text | |
</strong> | |
{% nospaces %} | |
Returns:: | |
<strong>Hello this is text</strong> | |
""" | |
nodelist = parser.parse(('endnospaces',)) | |
parser.delete_first_token() | |
return NoSpacesNode(nodelist) |
@kontur I would usually just react to a helpful comment, but since I can't in gist: thanks so much!
To add more context: I used Django 5.2.4
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use
from django.utils.encoding import force_str
for newer Django versions.