11

So I have this:

<%= link_to(image_tag(@model.picture.url(:thumb), :alt => ''), "/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) %>

Which works, but I need a span in between also like this:

 <a id="y_link_2" href="/pages/you/2" class="">
     <span>Apples</span>
     <img src="another_small.jpg?1236340989" alt="">
 </a>

How do I add

 <span>Apples</span>

to the link_to?

messivanio
  • 2,263
  • 18
  • 24
Matt Elhotiby
  • 43,028
  • 85
  • 218
  • 321

4 Answers4

18

Feed a block to your link_to call:

<% link_to("/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) do %>
  <%= content_tag(:span, 'Apples') %>
  <%= image_tag(@model.picture.url(:thumb), :alt => '') %>
<% end %>

Alternatively:

<% link_to("/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) do %>
  <span>Apples</span>
  <%= image_tag(@model.picture.url(:thumb), :alt => '') %>
<% end %>
Shaun
  • 4,789
  • 3
  • 22
  • 27
12

image_tag and content_tag return basic strings, so they can be concatenated using the + operator easily:

<%= link_to(content_tag(:span, "Apples") + image_tag(@model.picture.url(:thumb), :alt => ''), "/pages/you/#{something.id}", {:id => "y_link_#{something.id}"}) %>

However, as you can see, it gets quite messy - might be worth moving it into a helper method.

dnch
  • 9,565
  • 2
  • 38
  • 41
1

For a path, use the structure like so

<%= link_to edit_section_path(@section) do %>
   Edit
   <span class="fa fa-list pull-right"></span>
<% end %>
Pang
  • 9,564
  • 146
  • 81
  • 122
Sawo Cliff
  • 2,888
  • 1
  • 17
  • 21
0

Haml lends itself well to situations like these. For example:

= link_to "/pages/you/#{something.id}", id: "y_link_#{something.id} do
    %span Apples
    = image_tag(@model.picture.url(:thumb), alt: '')

Alternatively:

%a[something, 'y_link']{href: "/pages/you/#{something.id}"}
    %span Apples
    %img{src: @model.picture.url(:thumb)}

It's worth learning if you want to write your views faster and read them better.

Daryl Wright
  • 81
  • 1
  • 8