I have a text field in my model called 'about', which I'm trying to display on a show page, but none of the line breaks are showing up properly.
I've tried a number of things, but the code I finally landed on is:
<%= (h @template.about).gsub("\n", "<br />") %>
Unfortunately, Rails seems to be escaping the desired HTML and outputting these line breaks as
Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? <br />
How can I properly convert the text field's "\n" linebreaks into actual linebreak HTML? I've already tried simple format as well, to no avail...
I'm using Rails 3, and the first few lines of 'about' are:
Thanks for the fish, guys! Not like I wanted it, but... uh... thanks?
"I'll be the judge of that," he said!
And now, more useless copy so I can isolate that weird bud that Amanda found.
Wait! I meant 'weird bug...'
try
<%= simple_format @template.about %>
http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#method-i-simple_format
It works for me :-\
1.9.3p194 :017 > str = "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks?
1.9.3p194 :018"> \"I'll be the judge of that,\" he said!
1.9.3p194 :019"> And now, more useless copy so I can isolate that weird bud that Amanda found.
1.9.3p194 :020"> Wait! I meant 'weird bug..."
#=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n\"I'll be the judge of that,\" he said! \nAnd now, more useless copy so I can isolate that weird bud that Amanda found. \nWait! I meant 'weird bug..."
1.9.3p194 :021 > simple_format str
#=> "<p>Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? \n<br />\"I'll be the judge of that,\" he said! \n<br />And now, more useless copy so I can isolate that weird bud that Amanda found. \n<br />Wait! I meant 'weird bug...</p>"
or using gsub
1.9.3p194 :022 > str.gsub("\n", "<br />")
#=> "Thanks for the fish, guys! Not like I wanted it, but... uh... thanks? <br />\"I'll be the judge of that,\" he said! <br />And now, more useless copy so I can isolate that weird bud that Amanda found. <br />Wait! I meant 'weird bug..."
<%= (h @template.about).gsub("\n", "<br />").html_safe %>
The h
helper escapes the text so you aren't left open to XSS attacks. Once that text is escaped, you can gsub
and declare the new string to be html_safe
.
html_safe
is not escaping, it's the declaration that the string shouldn't be escaped. But you do want to escape the original string unless you are sure it does not contain user input.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With