带图像的按钮?

嘿家伙我正在尝试创建一个带图像的按钮。 基本上,我需要下面代码的button_to版本:|

 "img"), line_items_path(:product_id => product) %> 

这是我的解决方案:

使用按钮助手(您可以使用button_to助手方法):

 <%= f.submit 'Save', :class => "button_with_image_save" %> 

CSS:

 .button_with_image_save { background: url(../images/icons/page_save.png) #f2efa8 no-repeat 10px 6px; text-indent:30px; display:block; cursor: pointer; } 

这是一篇非常古老的post,但是为了将来的参考:从Rails 3.2.1开始,你可以使用button_tag而不是button_to ,因为第一个本身允许使用图像:

创建一个按钮元素,用于定义提交按钮,重置按钮或可在JavaScript中使用的通用按钮。 您可以将按钮标记用作常规提交标记,但在旧版浏览器中不支持。 但是,按钮标签允许更丰富的标签,如图像和强调,因此这个帮助器也将接受一个块。

至于你的例子:

 <%= button_tag image_tag(product.image_url), line_items_path(:product_id => product), class: 'img' %> 

我没有测试代码,但它应该工作。 您可能需要使用url:声明url:

你可以创建一个帮助器作为button_to链接 –

 <%= button_to product.image_url, line_items_path(:product_id => product) %> 

并在application_helper中

 def button_to(image_path, link) link_to (image_tag(image_path, :class => "img"), link) end 

我想这就是你想要的。

简短的回答是你需要创建一个辅助方法,这很简单:

这是一个类似的SOpost解释它: 是否有一种方式与rails表单助手生成一个按钮标签提交

祝好运

图片提交按钮:

 <%= image_submit_tag("team/team1.png", class: 'image-responsive') %> 

链接图片:

 <%= link_to(image_tag("team/team1.png", class: 'image-responsive'), root_path, :method => :get) %> 

添加图像是app / assets / image文件夹

在视图中

 <%= image_submit_tag('nameimage.png') %> 

缺点是您无法根据大小更改大小,但必须具有要显示的大小的图像