Ruby-on-rails Rails 3:link_to 和 image_tag
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7136194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 3: link_to and image_tag
提问by Coxn
How can I have an image tag linking to the file background.jpgin my public/images and when clicked on redirect the user to the root_url (So the content of the page is in a container and if the user clicks on the background image are redirected to home?) Thanks!
我怎样才能有一个图像标签链接到background.jpg我的公共/图像中的文件,当点击时将用户重定向到 root_url(所以页面的内容在一个容器中,如果用户点击背景图像被重定向到主页?) 谢谢!
回答by jschorr
Sure:
当然:
<%= link_to(image_tag("background.jpg", :alt => "home image", :width => 100, :height => 100, :title => "Click here to return to Home") "/") %>
回答by IAmNaN
Most of rails tag helpers accept a block, which means you can use doto simplify your life. Here I use a block with link_to:
大多数 rails 标签助手都接受一个块,这意味着你可以使用它do来简化你的生活。在这里,我使用了一个块link_to:
<%= link_to root_url do %>
<%= image_tag "background.jpg" %>
<% end %>
In this case, link_to expects the next parameter to be the path and the block emits what the anchor wraps.
在这种情况下,link_to 期望下一个参数是路径,并且块发出锚所包裹的内容。
In general I try to keep to the one tag helper per linerule unless its super trivial, so prefer this technique when the line would otherwise become crowded. An advantage to doing it this way is since tags are on different lines, errors are easier to identify.
一般来说,我尽量保持每行一个标签助手,除非它非常微不足道,所以当行变得拥挤时更喜欢这种技术。这样做的一个好处是因为标签位于不同的行上,所以更容易识别错误。
If you need other options to go with it, add them like you usually would. For example I'll add a css class:
如果您需要其他选项,请像往常一样添加它们。例如,我将添加一个 css 类:
<%= link_to root_url, :class => 'imagelink' do %>
...
回答by egyamado
I was searching for same thing while ago, and i found the Rails way to do so.
前段时间我一直在寻找同样的东西,我找到了 Rails 方法。
Lets say you want to you HTML page to render follwoing code
假设您希望 HTML 页面呈现以下代码
<a title="Return Home" class="logo" href="/pages/home">
<img width="200" height="50" src="logo.png" alt="Logo Image">
</a>
Where 'pages' is the controller and 'home' is the action. Here's the Rails way.
其中“pages”是控制器,“home”是动作。这是 Rails 的方式。
<%=link_to(image_tag("12roots-logo.png",:size => "209x50", :alt=> "12roots"),
{:controller=>"pages", :action=>"home"}, :title=>"Return Home", :class=>"logo") %>

