Login

Auto HTML Linebreak filter

Author:
punteney
Posted:
April 11, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This custom filter is helpful if you want to convert plain text to include html line breaks but you aren't sure if the text is actually plain text or if it already contains html line breaks.

First the filter looks for if the text contains any br, p, or table tags, if it does the text is returned as is. If it doesn't then the same functionality as the linebreaks filter is applied to the text.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def autolinebreaks(value, autoescape=None):
    """
    Checks if the content is html or plain text if plain text 
    replaces line breaks with appropriate HTML; a single
    newline becomes an HTML line break (``<br />``) and a new line
    followed by a blank line becomes a paragraph break (``</p>``).
    """
    import re
    html_match = re.compile('<br>|<br />|<p>|<table>', re.IGNORECASE)
    if not html_match.search(value):
        from django.utils.html import linebreaks
        autoescape = autoescape and not isinstance(value, SafeData)
        return mark_safe(linebreaks(value, autoescape))
    else:
        return value
autolinebreaks.is_safe = True
autolinebreaks.needs_autoescape = True
autolinebreaks = stringfilter(autolinebreaks)
register.filter(autolinebreaks)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 6 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 6 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 1 month ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 1 month ago
  5. Help text hyperlinks by sa2812 1 year, 2 months ago

Comments

Please login first before commenting.