ruby-on-railsrubyruby-on-rails-3sinatraerb

How to print a string in erb file including line breaks


After getting an input from a user, I'm having a string like so:

str = "First line/nSecond line/nThird line"

When I'm trying to print it in my erb file like so:

<%= str %>

I'm getting only one line without any line's breaks ("First line Second line Third line")

My question is:

How to print a string in erb file including the line's breaks?

(I guess i can replace every \n with <br> tag but I wonder if there's a better way of achieving that?!)


Solution

  • You tagged this question with ruby-on-rails. Therefore, I guess you want to output the text to a webpage.

    I suggest using the simple_format helper method like this:

    <%= simple_format(str) %>
    

    Example the docs:

    simple_format("Here is some basic text...\n...with a line break.")
    # => "<p>Here is some basic text...\n<br />...with a line break.</p>"