Login

Convert newlines into <p> and </p> tags

Author:
jheasly
Posted:
March 29, 2007
Language:
Python
Version:
.96
Tags:
filter
Score:
1 (after 1 ratings)

Based upon (i.e., mostly lifted from) the built-in "linebreaks" and "linebreaksbr" filters, this one works as they do:

{{ object.text|paragraphs }}

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
from django.template import Library, Node
from django.template.defaultfilters import stringfilter
import re

register = Library()

def paragraphs(value):
    """
    Turns paragraphs delineated with newline characters into
    paragraphs wrapped in <p> and </p> HTML tags.
    """
    paras = re.split(r'[\r\n]+', value)
    paras = ['<p>%s</p>' % p.strip() for p in paras]
    return '\n'.join(paras)
paragraphs = stringfilter(paragraphs)

register.filter(paragraphs)

More like this

  1. Template filter that divides a list into exact columns by davmuz 4 years, 7 months ago
  2. Link filter by sean2000 8 years, 8 months ago
  3. Analogue template filter to removetags that also removes the content of the tag by piquadrat 5 years, 9 months ago
  4. Bitwise operator queryset filter by [email protected] 6 years, 3 months ago
  5. Variable inspect filter by buriy 8 years, 3 months ago

Comments

Archatas (on March 30, 2007):
<p>I would simplify</p> <pre>value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines paras = re.split('\n', value) </pre> <p>to</p> <pre>paras = re.split(r'[\r\n]+', value) </pre>

#

jheasly (on April 9, 2007):
<p>@Archatas,</p> <p>Good suggestion. Thanks!</p>
  • jheasly

#

kernel32ddl (on June 23, 2011):
<p>buit-in tag in Django: linebreaks</p> <p>https://docs.djangoproject.com/en/dev/ref/templates/builtins/#linebreaks</p>

#

kernel32ddl (on June 23, 2011):
<p>Oh, sorry this tag add <br> into </p>

#

Please login first before commenting.