Jan
26
2007

Convert Line Breaks in Rails

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!

10 Comments + Add Comment

  • [...] Convert Line Breaks in Rails [...]

  • why don’t you take #simple_format ( http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000620 )? it does exactly what you want :-D thanks anyway,

    nick

  • thats sweet

  • thank you a lot

  • Nice one, actually your line_break method worked better than the simple format for me thanks

  • 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?

  • 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.

  • 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

  • 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”))

  • +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.

Leave a comment