nl2br in RoR

Posted by Gerald Abrencillo on January 31, 2008 
Filed Under Bugs and Fixes, Ruby on Rails

I recently found out that line breaks are not recognized when displaying a large block of text on the view (e.g. a post body). In PHP this was handled by the nl2br method but I had no luck finding a similar function in RoR. So I did what any sane person would do, create one myself. I placed this method in our model to format a particular field but it seems a better choice to put it in a helper.

def nl2br(text)

return text.gsub(/\n/, ‘<br/>’)

end

And there you have it, your very own nl2br method. Either you just found something really useful or I just wasted 2 minutes of your time. If anyone has a better solution or if I missed a function for this let us know by dropping a comment.

Comments

  • Nice one-liner. Thanks for sharing.
  • Gerald Abrencillo
    Thanks. I'll have to look into this.
  • If you're looking for a function that's view-related, check ActionView::Helpers. I never needed an nl2br method so far in my RoR projects, but after reading this post and checking the API, I found the TextHelper module with a method called simple_format. It's not exactly the same as nl2br because if you have 2 or more newlines, it wraps the content in p tags.
  • Gerald Abrencillo

    There's really no styling going on in the code. For example, if I post something like:


    Yey


    Boo


    If I retrieve it from the database and display it in the view, it will be displayed as:


    YeyBoo


    The nl2br function just changes all line breaks to '<br/>' so it will be displayed properly in the view. If there's an alternative let me know. It may come in handy in the future. :D

  • Ramon Tayag
    Don't you want to leave all formatting and styling for CSS nalang? :D
blog comments powered by Disqus