8

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?

0

4 Answers 4

4

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+

Sign up to request clarification or add additional context in comments.

Comments

2

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 }}

Comments

2

Use the linebreaksbr (or linebreaks) filter in your template.

For example:

{{ value|linebreaksbr }}

If value is Joel\nis a slug, the output will be Joel<br />is a slug.

Comments

0

The newlines are there, it just doesn't do anything in HTML.

Use a filter like {{ content|linebreaksbr }}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.