Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails seems to be auto-escaping html created by link_to

Here is my code, I'm trying to display a list of links to a bboy's crews in sentence form with .to_sentence

<span class="affiliation">
    <% if(@bboy.crews.count > 0)%>
    <span><%= if(@bboy.crews.size > 1) then "Crew".pluralize else "Crew" end %>:</span>
    <%= @bboy.crews.collect{|c| link_to c.name, c}.to_sentence %>
    <% else %>  
    <em>Independent</em>
    <% end %>
</span>

The output I get is the correct links but it displays as:

<a href="/crews/1">Hustle Kidz</a> and <a href="/crews/2">Knuckleheads Cali</a>

rather than:

Hustle Kidz and Knuckleheads Cali

with the html escaped, rather than the desired links.

Am I missing something? I've tried CGI.unescapeHTML and a few others but am getting lost...

like image 254
Chris M Avatar asked Mar 25 '11 15:03

Chris M


3 Answers

Rails 3 now automatically escapes everything, in order to output raw HTML use this:

<%= some_string.html_safe %>

or this:

<%= raw @some_html_string %>

Thanks to macek for a hint.

For additional details: http://markconnell.co.uk/posts/2010/02/rails-3-html-escaping

like image 58
Alex Kovshovik Avatar answered Nov 18 '22 08:11

Alex Kovshovik


You can (and should) you the raw method

<%= raw @some_html_string %>
like image 41
maček Avatar answered Nov 18 '22 08:11

maček


I agree with Kleber S, you should move this into a helper, because that's a lot of logic for a view

def crews_description(crews)
  if crews.empty?
    content_tag('em', 'Independent')
  else
    label = "Crew"
    label = label.pluralize if crews.size > 1
    crews_links = crews.map {|crew| link_to(h(crew.name), crew)}.to_sentence
    content_tag('span', label) + crews_links.html_safe
  end
end

and in your view:

<span class="affiliation">
  <%= crews_description(@bboy.crews)
</span>
like image 41
John Douthat Avatar answered Nov 18 '22 09:11

John Douthat