Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 %>
like image 562
rails3dev Avatar asked Apr 25 '12 09:04

rails3dev


2 Answers

<%= 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.

like image 58
shuriu Avatar answered Nov 19 '22 08:11

shuriu


why not just make a view helper 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 you views with link_to_delete

although why do you need your 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 dont like it as much 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 an a tag just change :span to :a

like image 1
nodrog Avatar answered Nov 19 '22 09:11

nodrog