Login

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

Author:
jheasly
Posted:
March 29, 2007
Language:
Python
Version:
.96
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 tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 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 <br> into

#

Please login first before commenting.