
Render Template Without Line Breaks Using a Django Template Tag This Django block template tag renders your templates without any line breaks. Be aware, it might mess up the content of forms so I recommend using it outside of them. This is the block tag I use on Uglek to serve the site without any line breaks in the base code.
# /project/app/app_filters.py
# Imports
from django import template
from django.utils.html import strip_tags
from django.template.base import Node
from django.utils.functional import keep_lazy
import six
register = template.Library() # Register template library
@register.tag
def linebreakless(parser, token):
nodelist = parser.parse(('endlinebreakless',))
parser.delete_first_token() # Delete tags from the template
return LinebreaklessNode(nodelist) # Render the node without line breaks
class LinebreaklessNode(Node):
def __init__(self, nodelist):
self.nodelist = nodelist # Initialize with nodelist
def render(self, context):
strip_line_breaks = keep_lazy(six.text_type)(lambda x: x.replace('\n', '')) # Using keep lazy
return strip_line_breaks(self.nodelist.render(context).strip()) # Strip the line breaks and return the node
{% linebreakless %}This is some text here. This will render without a line break{% endlinebreakless %}
Comments (0) Comment
© Uglek, 2022