Reputation: 29514
I want to output the following with Ruby on Rails link_to
and image_tag
methods:
<a href="#">Lorem Ipsum <img src="/images/menu-arrow-down.gif"></a>
What would be a good way in Rails?
Upvotes: 44
Views: 59545
Reputation: 144
For me this worked just fine:
<%= link_to(image_tag(<URL>,style),<URL>) %>
Upvotes: 1
Reputation: 38012
You can use blocks as an alternative to the string interpolation with correct usage html_safe
. For example:
<%= link_to '#' do %>
Lorem Ipsum <%= image_tag('/images/menu-arrow-down.gif') %>
<% end %>
Upvotes: 91
Reputation: 271
Here's a cool way to use a link_to to include an image, and a mailto href with Text (displayed next to the image):
<%= link_to image_tag("image.png") + " [email protected]",
href: "mailto:[email protected]" %>
Giving you something like this in your view (the entire image and text become an mailto href):
Upvotes: 2
Reputation: 489
Or a shorter way is
<%= link_to image_tag('image/someimage.png') + "Some text", some_path %>
Upvotes: 35
Reputation: 6410
I prefer this approach in HAML
= link_to root_path do
= image_tag "ic_launcher.png", size: "16x16"
Home
Upvotes: 2
Reputation: 1
i found out this also which worked.
link_to(image_tag("/images/linkd.png",:alt=>"twt"){},:href=>"some_url",:target=>"_blank")
Upvotes: 0
Reputation: 21564
Why not just use a link to and image tag?
<%= link_to "hiii #{image_tag(yourimagepath)}", "link_path" %>
You could also try the appending done above (string + image_tag
), but it will throw an error if one of those things becomes nil
. Using interpolation, it will just show a blank image(or string) if it is nil
.
For Rails 3, you will need to use html_safe
:
<%= link_to "hiii #{image_tag(yourimagepath)}".html_safe, "link_path" %>
Upvotes: 33
Reputation: 569
I cannot seem to figure out how to add a comment to @corroded's answer. However, if you are using Rails 3, his answer will not work as expected. It might not be immediately obvious how to fix this, at least it wasn't for me. I knew I needed to add html_safe, but put it in the wrong place. In retrospect, it was obvious, but I thought I would include it here for others like me who make the "rookie" mistake.
<%= link_to "hiii #{image_tag(yourimagepath)}".html_safe, "link_path" %>
be careful though, if you are using a user assignable variable for "hiii" you need to sanitize it first.
<%= link_to (h(my_model.some_string) + image_tag(yourimagepath)).html_safe,
"link_path" %>
Note that there is no issue with my_model.some_string or yourimagepath being nil because both h() and image_tag() return strings when passed nil.
Upvotes: 3
Reputation: 4403
link_to(image_tag("image.png", :alt => "alt text", :class =>"anyclass"), image_url)
Upvotes: 4