Since the upgrade to rails 3, I face a new problem with displaying html from an array with different html tags.
so far I could just write the method_name witch returns a array of different html tags. (even if they were done by strings...)
Now the array gets displayed as a array:
["<br/></br/>", "<b><a href=\"/...">...</a></b>,"<br/></br/>"]
How is it possible to output this as html tags? I tried to run to_html at the end of every array entry, but this gave mi the error:
undefined method `to_html' for "<br/></br/>":ActiveSupport::SafeBuffer
Any ideas how to fix this?
Thanks Markus
Update: Thanks to the answer of nimblegorilla the output looks now like:
["
", "...","
"]
This is something better, because the html is removed, but the elements get still displayed as an array...
I think you are looking for the 'raw' method:
<% array = ["<br/>Hello World</br/>", "<b><a href=\"/...\">...</a></b>" , "<br/><b>Yo</b></br/>"] %>
<%= raw array %>
This makes sure that you intended to display the html as actual html as opposed to untrusted input from a user that might be a possible XSS attempt.
This railscast talks about it a little more: http://railscasts.com/episodes/204-xss-protection-in-rails-3
To answer your later question: because you are indeed outputting an array...
<% array = ["<br/>Hello World</br/>", "<b><a href=\"/...\">...</a></b>" , "<br/><b>Yo</b></br/>"] %>
you could do:
<%= raw(array.join) %>
or:
<%= array.join.html_safe %>
Calling .html_safe on any string will convert it to SafeBuffer, which Rails doesn't escape. So it's the same as calling "raw" method... but I personally like .html_safe
more, especially in my helpers...
You can for example:
module ApplicationHelper
# links will be converted to array, if multiple items are passed
def ext_links(*links)
links.map { |l|
link_to("external link: <span>#{l}</span>".html_safe, l)
}.join.html_safe
end
end
And then use this in your view, without need of calling it through "raw":
<%= ext_links("http://google.com", "http://seznam.cz") %>
Or
<%= ext_links(["http://google.com", "http://seznam.cz"]) %>
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