Adding buttons and icons
In this section we will learn how to style the Edit
and Delete
links for the posts.
Buttons
Looking in the Bootstrap documentation for buttons, we see that the addition of certain classes can make our links look like buttons.
Let's start with the Edit button. For my example, I've selected the button style to have a default color and an extra small size. Thus, instead of:
<%=link_to("Edit", edit_post_path(post)) %>
we can use:
<%= link_to("Edit", edit_post_path(post), class: "btn btn-default btn-xs pull-right") %>
We will also move this button to the right, for convenience. To do this, Bootstrap provides some helper classes.
Let's do the same thing for the Delete button, while making sure it reflects a dangerous action:
<%= link_to("Delete", post_path(post), method: :delete, class: "btn btn-danger btn-xs pull-right") %>
This is how the links block should look:
<% if current_user == post.user %>
<%= link_to("Delete", post_path(post), method: :delete, class: "btn btn-danger btn-xs pull-right") %>
<%= link_to("Edit", edit_post_path(post), class: "btn btn-default btn-xs pull-right") %>
<% end %>
This is what it looks like in my application:
Icons
A picture is worth a thousand words. Bootstrap comes with set of icons that can be easily integrated in your site. Let's try to add one to the edit button!
The examples show that the icon should be placed within the button. However, since we're not using an a tag, but a link_to
, we'll have to write the code inside it. link_to
allows us to do it by removing the title and placing it inside a do ... end structure.
This is how we do it for the Edit
and Delete
buttons:
<%= link_to(edit_post_path(post), class: "btn btn-default btn-xs pull-right") do %>
Edit
<% end %>
<%= link_to(post_path(post), method: :delete, class: "btn btn-danger btn-xs pull-right") do %>
Delete
<% end %>
Note that I took the "Edit" (and, respectively, "Delete") string from being the first argument for link_to
and place it inside the do ... end
. This works exactly like the previous version, but now we can easily add more content between the do and the end:
<%= link_to(edit_post_path(post), class: 'btn btn-default btn-xs pull-right') do %>
<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit
<% end %>
<%= link_to(post_path(post), method: :delete, class: 'btn btn-danger btn-xs pull-right') do %>
<span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete
<% end %>
Done!