如何在Rails中将图像转换为链接?

49

我只想在一张图片上面添加一个简单的链接。

<a href="http://www.mysite.com"><img src="path/to/image.png"/></a>

如何使用link_to Rails标签实现此操作?

5个回答

79

link_to的内容中使用image_tag

link_to image_tag("path/to/image.png"), "http://www.mysite.com/"

1
谢谢,它起作用了。我忘记问你如何向图像添加类或ID了? - Spencer Cooley
7
没事了,我自己解决了。link_to image_tag("path/to/image.png", :class => "class_name"), "http://www.google.com/" - Spencer Cooley

30

我的解决方案:

<%= link_to root_path do %>
   <%= image_tag "image.jpg", class: "some css class here" %>
<% end %>

1
这个答案对我来说更好,因为我不必去处理我的image_tag的语法,使它与link_to协调。 - adg
嗨,我正在做这个。但是我得到了一个小框框,而不是我的图片。所以它找到了这张图片,但出于某种原因无法呈现它。你有什么建议吗? - Jessica

11

干燥的一件事
在你的application_helper.rb文件中

def link_to_image(image_path, target_link,options={})
  link_to(image_tag(image_path, :border => "0"), target_link, options)
end

然后从你的视图中获取

<%= link_to_image("path/to/image", some_url) %>

7
<%= link_to(image_tag("path/to/image.png"), root_path) %>

root_path 是您网站主页的路由。


3
<%= link_to root_path do %>
    <%= image_tag "img.png", height: 27 %>
<% end%>

将root_path和img.png替换为您的路径和图像名称。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接