Rails 3.2 using content_tag to generate a 'Delete' button with twitter-bootstrap icons

rails3dev picture rails3dev · Apr 25, 2012 · Viewed 40k times · Source

I'm trying to replicate the Delete button icon in this example using the Rails 3 content_tag method, within a nested form and using jQuery unobtrusively (or at least I hope to be).

Twitter-Bootstrap Delete Button icon (example)

The html produced in when inspecting with Firebug is below.

<a class="btn btn-danger" href="#">
  <i class="icon-trash icon-white"></i>
  Delete
</a>

I'm using the following to generate the button with an icon but cannot add the "Delete Ingredients" to it, nor do I get the "#" for the href.

Here is my code from within the ingredients partial:

<%= link_to content_tag(:a, content_tag(:i, '', class: "icon-trash icon-white"), class: "btn btn-danger remove_fields") %>

This generates:

<a class="btn btn-danger remove_fields">
  <i class=icon-trash icon-white"></i>
</a>

This was based on information from Api dock - content_tag

which had the following code example:

content_tag(:div, content_tag(:p, "Hello world!"), :class => "strong")
# => <div class="strong"><p>Hello world!</p></div>

Can someone kindly point me in the right direction? Why am I missing details I mentioned above?

N.B. I can get this to work with a link_to block but wanted to know if this can be done in one line without the do..end and more importantly in a content_for method.

<%= link_to('#', class: "btn btn-danger remove_fields") do %>
  <i class: "icon-trash icon-white"></i>
  Delete
<% end %>

Answer

shuriu picture shuriu · Apr 30, 2012
<%= link_to(body, url, html_options = {}) %>

So your request in 1 line is:

<%= link_to content_tag(:i, "", class: "icon-trash icon-white") + "Delete", path_to_stuff, method: :delete, class: "btn btn-danger remove_fields" %>

The most complicated part is the 'body'. You just have to remember that all these content_tag helpers (including link_to and others), return a string.

BUT, this is ugly. AND long. AND hard to maintain. So your proposed solution that takes the block is much better.