Add newline using / n in text variable
I have a variable in my view, printed to the screen as
<%= comment.comment %>
but there are many new string characters ( \n
) in the output .
How do I get it to actually print new lines whenever we have output \n
from comment.comment
?
Try the following:
<%= comment.comment.gsub(/\n/, '<br />') %>
Alternatively, you can also use simple_format
. Here:
<%= simple_format(comment.comment) %>
Its rendering is HTML. So you need to convert newlines to html br tag. Try simple_format http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
HTML interprets newlines as spaces, except for elements where CSS sets white-space
to pre
, pre-line
or pre-wrap
(for example, the <pre>
default element ).
Thus, you can do one of the following:
<pre><%= comment.comment %></pre>
<style> .with-newlines { white-space: pre } </style>
<div class=".with-newlines"><%= comment.comment %></div>
<%= comment.comment.gsub(/\n/, '<br>') %>
Try the following:
<%= comment.comment.dump %>