Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Twitter Bootstrap button icon to button_to in Rails

I am working through the Agile Web Development with Rails book but I have been using Twitter Bootstrap instead of the custom styling from the book. I am having trouble adding an icon through GLyphonics to the button_to method. My code looks like this:

<%= button_to <i class="icon-search icon-white">Add To Cart</i>, 
              line_items_path(product_id: product), 
              class: "btn btn-success" %>

I have tried quite a few variations but can't seem to get it to work correctly.

like image 607
maddiedog Avatar asked May 06 '12 04:05

maddiedog


3 Answers

I'm not sure how the OP got this to work, but Rails button_to generates an <input type='submit' /> element, which does not allow for HTML in the value field.

See also: input type="submit" Vs button tag are they interchangeable?

The best alternative in this situation is to force link_to to PUT (or POST):

<%= link_to raw("<i class=\"icon-search icon-white\">Add To Cart</i>"), 
          line_items_path(product_id: product), 
          class: "btn btn-success",
          method: :put %>
like image 88
jordanpg Avatar answered Nov 12 '22 10:11

jordanpg


You can add the icon as a child element:

<%= button_to button_path, method: :delete do %>
    <span class="glyphicon glyphicon-search"></span>
<% end %>
like image 43
DanT Avatar answered Nov 12 '22 10:11

DanT


It looks like you have an issue with your quotes:

<%= button_to raw("<i class=\"icon-search icon-white\">Add To Cart</i>"), 
          line_items_path(product_id: product), 
          class: "btn btn-success" %>

Enclose the label of the button in double quotes, escape the double quotes in your i tag, and finally, wrap everything into a raw() call to ensure the HTML is properly displayed.

Alternatively you can use html_safe:

<%= button_to "<i class=\"icon-search icon-white\">Add To Cart</i>".html_safe, 
          line_items_path(product_id: product), 
          class: "btn btn-success" %>

good point from @jordanpg: you can't have HTML in the value of a button, so his solution is more appropriate and should get the approved status. the html_safepart remains valid though.

like image 7
Pierre Avatar answered Nov 12 '22 12:11

Pierre