Rails -- Add a line break into a text area

Line breaks in textareas are produced as `\n'. However, the problem is that if you simply dump it into your view, it will just be line breaks in your HTML source.

You can try using the Rails simple_format helper to take care of some of this for you: http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M002285

It will auto-convert line breaks to HTML tags. You can use it with something like <%= simple_format(my_text_field) %>.


The problem isn't so much editing the value as it is rendering it later. To add newline characters to your value while editing it in a textarea, just hit the return key. When you re-edit that value later, the whitespace should still be there.

Rendering the whitespace is the tricky part. In HTML, whitespace is generally insignificant. A renderer like the one your browser uses will display a single space for any continuous string of whitespace. So merely dumping the value onto the page won't be enough:

<%= obj.description %>

Even though your value may be "One \t \n \n Two", it will show up on the screen as "One Two".

To get those new line characters to actually separate the lines when displayed, you'll need to convert them to HTML before rendering:

<%= obj.description.gsub(/\n/, '<br/>') %>

Of course, if users are entering data that will be included in your HTML, you should be escaping the values to protect against XSS. If new lines are the only thing you need to support, it should be as simple as this:

<%= h(obj.description).gsub(/\n/, '<br/>') %>

If you want to allow more complex formatting, look into Markdown and Textile (both of which Rails provides helper view methods for). Just be sure to investigate what if any support they provide for XSS prevention.


Keep user input unmodified and add this to your css:

white-space: pre-line;

It will display \r or \n (enter) in user input as a new line.