Django Filter Tag To Remove New Lines

For example, you want your application metatags not to have new line characters. Very useful when creating we applications that need sharing links on social medias.

Here is a tag to remove and replace all new lines from a string :

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django import template
from django.utils.safestring import mark_safe
from django.template.defaultfilters import stringfilter
from django.utils.text import normalize_newlines

register = template.Library()

@register.filter
def remove_new_lines(text, replacement=' '):
    """
    Removes and replaces all newline characters from a block of text.
    default replacement=' '
    """
    # Normalize new lines
    normalized_text = normalize_newlines(text)
    # Replace newlines with replacement
    return mark_safe(normalized_text.replace('\n', replacement))

To use it in your template files:

First load the tag:

1
{% load  remove_new_lines%}

Then use as:

1
{{object.description  | remove_new_lines}}

Related Posts

0 Comments

12345

    00