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:
| {% load remove_new_lines%}
|
Then use as:
| {{object.description | remove_new_lines}}
|