views:

148

answers:

2

I'm using python with pylons

I want to display the saved data from a textarea in a mako file with new lines formatted correctly for display

Is this the best way of doing it?

> ${c.info['about_me'].replace("\n", "<br />") | n}
+1  A: 

It seems to me that is perfectly suitable.

Be aware that replace() returns a copy of the original string and does not modify it in place. So since this replacement is only for display purposes it should work just fine.

Here is a little visual example:

>>> s = """This is my paragraph.
... 
... I like paragraphs.
... """
>>> print s.replace('\n', '<br />')
This is my paragraph.<br /><br />I like paragraphs.<br />
>>> print s
This is my paragraph.

I like paragraphs.

The original string remains unchanged. So... Is this the best way of doing it?

Ask yourself: Does it work? Did it get the job done quickly without resorting to horrible hacks? Then yes, it is the best way.

jathanism
+1  A: 

Beware as line breaks in <textarea>s should get submitted as \r\n according to http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4

To be safe, try s.replace('\r\n', '<br />') then s.replace('\n', '<br />').

ccmonkey
I'd go for `'<br />'.join(s.splitlines())`.
Devin Jeanpierre