Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read back and print text with newlines from a Python (Django) string with HTML?

If someone types in a phrase, such as:

I see you driving

round town with the girl I love,

and I’m like: haiku.

(no blank lines between each line, but the text is written on three separate lines) into a text box on a web page, and then presses a button which is then stored in a database via Django, and that string is read back and printed on a page, how can I get it to print on an HTML page with the newlines still in the text?

So instead of it being printed back as: I see you driving round town with the girl I love, and I’m like: haiku.

It would print as:

I see you driving

round town with the girl I love,

and I’m like: haiku.

I know that if I use: (textarea)soAndSo.body(/textarea), this preserves the newlines that were in the file when the user typed it up originally. How can I get this same effect, but without having to use textarea boxes?

like image 488
user1801486 Avatar asked Nov 05 '12 22:11

user1801486


2 Answers

While having linebreak symbols \r\n replaced with a <br/> is definitely an option, you may want to consider css white-space property:

#haiku {white-space:pre;}

Fiddled, worth noting that the property is surprisingly well-supported, even on IE6+

like image 169
Oleg Avatar answered Oct 06 '22 19:10

Oleg


Wrapping the output in <pre> will preserve formatting, <pre>soAndSo.body</pre>

A more advanced solution involves turning the newlines into HTML paragraphs or line breaks. Django has built-in filters for this: Both linebreaks and linebreaksbr can do the trick.

If you want to use those, filter the output like so: {{ soAndSo.body|linebreaks }}

like image 21
vicvicvic Avatar answered Oct 06 '22 19:10

vicvicvic