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

 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 2 years, 2 months ago
  2. Link filter by sean2000 6 years, 4 months ago
  3. Analogue template filter to removetags that also removes the content of the tag by piquadrat 3 years, 5 months ago
  4. Bitwise operator queryset filter by hgeerts@osso.nl 3 years, 11 months ago
  5. Variable inspect filter by buriy 5 years, 11 months ago

Comments

Archatas (on March 30, 2007):

I would simplify

value = re.sub(r'\r\n|\r|\n', '\n', value) # normalize newlines
paras = re.split('\n', value)

to

paras = re.split(r'[\r\n]+', value)

#

jheasly (on April 9, 2007):

@Archatas,

Good suggestion. Thanks!

  • jheasly

#

kernel32ddl (on June 23, 2011):

buit-in tag in Django: linebreaks

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#linebreaks

#

kernel32ddl (on June 23, 2011):

Oh, sorry this tag add [HTML_REMOVED] into [HTML_REMOVED][HTML_REMOVED]

#

(Forgotten your password?)