8

Here's the string I want:

<a href="/pugs/1-baxter">Baxter</a> and <a href="/pugs/2-sofia">Sofia</a>

Here's the code I'm using to output that:

<%= @pugs.collect {|p| link_to(p.name, pug_path(p))}.to_sentence %>

Unfortunately the output is getting encoded:

 &lt;a href=&quot;/pugs/1-baxter&quot;&gt;Baxter&lt;/a&gt; and &lt;a href=&quot;/pugs/2-sofia&quot;&gt;Sofia&lt;/a&gt;

I've tried using html_safe and raw, but they don't seem to have any affect.

Shpigford
  • 24,748
  • 58
  • 163
  • 252

4 Answers4

9

As of Rails 5, there's a to_sentence view helper (different from Array#to_sentence) that does this.

From the docs:

to_sentence(array, options = {})
Converts the array to a comma-separated sentence where the last element is joined by the connector word. This is the html_safe-aware version of ActiveSupport's Array#to_sentence.

Use it like: <% to_sentence(@pugs.collect {|p| link_to(p.name, pug_path(p))}) %>

George Kagan
  • 5,913
  • 8
  • 46
  • 50
hynkle
  • 301
  • 4
  • 6
2
<%= @pugs.collect {|p| link_to(p.name, pug_path(p))}.to_sentence.html_safe %>
AMIT
  • 539
  • 1
  • 4
  • 13
  • It actually works. There is probably something else wrong then :) – AMIT Mar 14 '12 at 16:37
  • 5
    This is bad. You're marking the whole string as safe. If you set p.name to something malicious you'll see that your method allows it to get through unescaped into the page. – Brendon Muir May 01 '14 at 04:15
1

If you want to put it in a translation, you can add _html at the end of the translation key like this:

<%= t(".public_rooms_html", rooms: to_sentence(@public_rooms.map { |room| link_to(room.to_s, room) })) %>
Dorian
  • 7,749
  • 4
  • 38
  • 57
1

You could wrap it in a span and use a helper:

  def content_link_to(name,path=nil,options=nil)
    content_tag :span do
      link_to name, path, options
    end
  end

And use it as follows:

<%= @pugs.collect {|p| content_link_to(p.name, pug_path(p))}.to_sentence %>
Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
  • Adding extra HTML around those links just to output html safe content seems overkill. I just want Rails to output actual HTML instead of escaping it. – Shpigford Mar 14 '12 at 13:51