Convert Line Breaks in Rails
Posted by benrobb on January 26th, 2007
This may not be news to anyone else, but it was a surprise to me when I ran into it, so I thought perhaps someone else might find it helpful. Let’s imagine that you’ve got a form with a textarea that allows for a decent amount of user input, like, say a blog post or a news item on your family website.
When you push the “Enter” key it goes down to the next line. Behind the scenes, this is stored in your database as a new line character which is represented by “\n”. The problem is that “\n” has no meaning to a web browser. In web browser language, what you really need is a line break represented by the “<br />” tag. So how do you get all your new lines to turn into line breaks? The answer is one simple method added to your application_helper.rb file in your Rails project.
def line_break(string)
string.gsub("\n", '<br/>')
end
Then in your view, you simply call the line_break method around the appropriate block of text
<%= line_break(@news.body) %>
and that’s all there is to it!
January 26th, 2007 at 11:02 am
[...] Convert Line Breaks in Rails [...]
February 2nd, 2007 at 1:55 pm
why don’t you take #simple_format ( http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000620 )? it does exactly what you want
thanks anyway,
nick
March 6th, 2008 at 11:21 pm
thats sweet
May 10th, 2009 at 2:33 pm
thank you a lot
September 7th, 2009 at 5:51 am
Nice one, actually your line_break method worked better than the simple format for me thanks
March 26th, 2010 at 7:08 pm
Tried this out, but instead of getting an actual line break I get the line break html tag embedded in the middle of my entry. Do I need to remove the helper from the original tag to make this work?
March 29th, 2010 at 2:36 pm
Hopefully someone else can answer this one. I wrote this originally over 3 years ago, and I haven’t kept up to speed with Ruby.
November 19th, 2010 at 11:25 am
Adam:
You probably need to add .html_safe at the end of your string. The problem with that, though, is that will allow any html in the string to work, and if it’s user-inputted, that is a security hole. So, I’m searching for a good way to do this myself at present.
Kirkland
November 19th, 2010 at 12:02 pm
Okay, figured it out. Use the simple_format(“your text\nhere”) helper, but in order to still escape html, do simple_format(h(“your text\nhere”))
October 26th, 2011 at 8:43 am
+1 for @Kirkland’s .html_safe at the end of the string if you can afford to. We have some user gen content, but it has to go through a manual approval process, so I think its safe for us.