1

I have a helper method that returns a string after formatting it, which includes adding line breaks.

I am calling this helper method in a view and am trying to display this formatted string.

I am using "\n" or "\r\n" to introduce line breaks, but this shows up as mere spaces in the browser.

user1175969
  • 540
  • 6
  • 19
  • You may want to take a look at https://stackoverflow.com/a/17923431/7151673 and https://stackoverflow.com/a/8405339/7151673. These are specific answers to those questions, as I'm not a fan of the accepted answers on either question. – Max Dec 04 '16 at 23:26

2 Answers2

1

You should use <br> or create it like tag('br'):

your_string = "test string" + tag('br')
your_string.html_safe   #return your string

As @max rightly pointed, from a security vulnerability (XSS) aspect you can use h() on user-provided text, which converts your string to a safe string and allows you to securely call html_safe on the full string.

Max
  • 1,817
  • 1
  • 10
  • 13
dp7
  • 6,651
  • 1
  • 18
  • 37
  • 2
    If you call `html_safe`, make sure that the rest of your string _is_ safe for HTML output, or you'll have a security vulnerability (XSS). Either it needs to be a string that you have full control over (like explicitly using `"test string"`) or you need to call escaping functions on the user-inputted part of the string before calling `html_safe` on the combined string.. – Max Dec 04 '16 at 18:43
  • Glad to help! But `raw(some_string)` is actually the same as `some_string.html_safe`, as can be seen if you look at the source for [`raw`](http://apidock.com/rails/ActionView/Helpers/OutputSafetyHelper/raw). It doesn't escape anything--it actually turns off Rails' default escaping for that string. One option is [`safe_join`](http://apidock.com/rails/v4.2.7/ActionView/Helpers/OutputSafetyHelper/safe_join). See also https://stackoverflow.com/questions/4251284/raw-vs-html-safe-vs-h-to-unescape-html. – Max Dec 04 '16 at 21:23
0

One mistake i made was using raw(string) in the helper method instead of using it in view and it still was shown as 'smth
smth' so be aware of that.

My code looked something like this

td= helper_method()

And when I changed it to the following it worked:

td= raw(helper_method())
Thevel0per
  • 1
  • 1
  • 1