Rails 3.2 using content_tag to create a delete button with Twitter upload icons

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

Twitter-Bootstrap Delete Icon (Example)

Created by html when checking with Firebug below.

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

I use the following to generate a button with an icon, but I canโ€™t add โ€œDelete Ingredientsโ€ to it, nor can I get a โ€œ#โ€ for href.

Here is my code from part of the ingredients:

 <%= 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 the 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 the information I mentioned above?

NB I can get this to work with the link_to block, but I would like to know if it can be done on the same line without do..end and, more importantly, in the content_for method.

 <%= link_to('#', class: "btn btn-danger remove_fields") do %> <i class: "icon-trash icon-white"></i> Delete <% end %> 
+7
source share
2 answers
 <%= link_to(body, url, html_options = {}) %> 

So your query in 1 line:

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

The hardest part is the "body." You just need to remember that all of these content_tag helpers (including link_to and others) return a string.

BUT, this is ugly. And for a long time. And it's hard to maintain. So, your proposed solution, which occupies the block, is much better.

+3
source

why not just make an auxiliary representation method

 def link_to_delete link_to %{<i class="icon-trash icon-white"></i> Delete}, '#', class: "btn btn-danger remove_fields" end 

then call it in the form with link_to_delete

although why do you need it to be a link

 def delete_button %{<span class="btn btn-danger remove_fields"><i class="icon-trash icon-white"></i> Delete</span>} end 

I don't like this with content_for, but:

 content_tag(:span, %{#{content_tag(:i, nil, :class => "icon-trash icon-white")} Delete}.html_safe, :class => "btn btn-danger remove_fields") 

if you want it with a tag just change :span to :a

+1
source

All Articles