Ruby on Rails Helper Method - HTML is displayed as plain text
16,430
Solution 1
The result of your helper needs to be marked as "html_safe" in Rails 3. Otherwise, the tags will be escaped.
def my_helper
data = "<p>Hello!</p>"
data.html_safe
end
Solution 2
I suppose it was a problem with Rails html sanitize. from rails changelog
You no longer need to call h(string) to escape HTML output, it is on by default in all view templates. If you want the unescaped string, call raw(string).
try it
Solution 3
One thing to watch out for is when joining multiple strings like this
def custom_check_box(checked)
'<span class="my-custom-checkbox '+( checked ? 'checked' : '')+'"></span>'.html_safe
end
In this case, only the last part is marked as html safe. Make sure you get the whole thing.
def custom_check_box(checked)
('<span class="my-custom-checkbox '+( checked ? 'checked' : '')+'"></span>').html_safe
end
Author by
SZH
Updated on June 06, 2022Comments
-
SZH almost 2 years
I have a helper method for my Rails app that returns a string with HTML code for a Google Groups subscription form. Unfortunately, it comes out on the page like plain text. How can I force it to render as HTML? Thanks in advance.
-
SZH over 13 yearsI tried to accept the answer before, but it said I needed to wait 8 more minutes. Now it let me.