Rails 3: how to return the original contents of an array filled with html tags

Since upgrading to rails 3, I have a new problem with displaying html from an array with various html tags.

So far, I could just write the name of the method. witch returns an array of different html tags. (even if they were made in lines ...)

Now the array will be displayed as an array:

["<br/></br/>", "<b><a href=\"/...">...</a></b>,"<br/></br/>"] 

How can this be output as html tags? I tried to run to_html at the end of each array entry, but this gave mi an error:

 undefined method `to_html' for "<br/></br/>":ActiveSupport::SafeBuffer 

Any ideas how to fix this?

Thanks Marcus

Update:. Thanks to nimblegorilla's answer, the output is as follows:

 [" ", "..."," "] 

This is better because html is deleted, but elements are still displayed as an array ...

+4
source share
2 answers

I think you are looking for a "raw" method:

 <% array = ["<br/>Hello World</br/>", "<b><a href=\"/...\">...</a></b>" , "<br/><b>Yo</b></br/>"] %> <%= raw array %> 

This ensures that you intend to display html as actual html, and not untrusted input from the user, which might be a possible XSS attempt.

This railscast talks a little more about it: http://railscasts.com/episodes/204-xss-protection-in-rails-3

+5
source

To answer your later question: because you are really issuing an array ...

 <% array = ["<br/>Hello World</br/>", "<b><a href=\"/...\">...</a></b>" , "<br/><b>Yo</b></br/>"] %> 

You can do:

 <%= raw(array.join) %> 

or

 <%= array.join.html_safe %> 

Calling .html_safe for any string will convert it to SafeBuffer, which does not remove Rails. So this is the same as calling the 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 having to call it "raw":

 <%= ext_links("http://google.com", "http://seznam.cz") %> 

or

 <%= ext_links(["http://google.com", "http://seznam.cz"]) %> 
+3
source

All Articles