Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3: how to return raw content of an array filled with html tags

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...

like image 665
Markus Avatar asked Feb 25 '23 14:02

Markus


2 Answers

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

like image 155
nimblegorilla Avatar answered Apr 26 '23 03:04

nimblegorilla


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"]) %>
like image 23
Dalibor Filus Avatar answered Apr 26 '23 02:04

Dalibor Filus