Rendering newlines in user-submitted content (Python web app)

Paxwell picture Paxwell · Jul 6, 2012 · Viewed 9.3k times · Source

I have a web.py app that takes input from a textarea and inputs it to a database. I can get the information from the database and post it to the page but the NEWLINES are gone. How do I preserver newlines when posting back into HTML? The data does have \r\n in it but that isn't rendered as NEWLINES in HTML. Any thoughts? Here is a small example:

(2, u'Title', u'content here...hey\r\nthis\r\nhas\r\nbreaks in it....?', 
    datetime.datetime(2012, 7, 5, 21, 5, 14, 354516))

That is my return from the data base. I need the \r\n to represent a <br /> and if there is two a <p> would be awesome. Any direction would be very much appreciated.

Also is there a library for this? I have heard of markdown and mark up but I can find no examples of how to post html data from python strings?

Answer

Burhan Khalid picture Burhan Khalid · Jul 7, 2012

Two main ways to do this. The easiest one is to wrap the output in <pre></pre> which will format it as entered.

Or, you can replace newlies with <br /> (and not with <p>) as the characters represent a line break and not a paragraph.

For the second option, this is one approach:

>>> s
'hello\nthere\r\nthis\n\ris a test'
>>> r = '<br />'
>>> s.replace('\r\n',r).replace('\n\r',r).replace('\r',r).replace('\n',r)
'hello<br />there<br />this<br />is a test'
>>> 

Or the third option - which is to use one of the many text entry libraries/formats and render the content through them (as mentioned by others - like markdown).

However, that would be overkill if all you want to do is a simple replace.