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?
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+
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 }}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With