Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to_sentence and html_safe, together?

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.

like image 592
Shpigford Avatar asked Mar 14 '12 05:03

Shpigford


3 Answers

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))}) %>

like image 136
hynkle Avatar answered Sep 18 '22 18:09

hynkle


<%= @pugs.collect {|p| link_to(p.name, pug_path(p))}.to_sentence.html_safe %>
like image 32
AMIT Avatar answered Sep 19 '22 18:09

AMIT


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 %>
like image 33
Michael Durrant Avatar answered Sep 21 '22 18:09

Michael Durrant