Convert Line Breaks in Rails

Posted by 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!

This entry was posted on Friday, January 26th, 2007 at 10:55 am and is filed under Rails. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

 

10 Responses to “Convert Line Breaks in Rails”

  1. benrobb » Blog Archive » Rails Tips & Tricks Says:

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

  2. Nick Sutterer Says:

    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

  3. S Says:

    thats sweet

  4. Sebastian Says:

    thank you a lot

  5. conspirisi Says:

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

  6. Adam Noveskey Says:

    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?

  7. benrobb Says:

    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.

  8. Kirkland Says:

    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

  9. Kirkland Says:

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

  10. Eric Fields Says:

    +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 Reply