Quick tip 3 - Adding buttons

Hi everyone! As we've been adding features to our website and, up to this point, it now looks like this:

In this section we will learn how to style the Edit and Delete links for the posts.

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_case_path(c)) %>

we can use:

<%= link_to("Edit", edit_case_path(c), class: 'btn btn-default btn-xs') %>

We will also move this button to the right, for convenience. To do this, Bootstrap provides some helper classes.

This is what we end up with:

<%= link_to("Edit", edit_case_path(c), class: 'btn btn-default btn-xs pull-right') %>

Let's do the same thing for the Delete button, while making sure it reflects a dangerous action:

<%= link_to("Delete", case_path(c), method: :delete, class: 'btn btn-danger btn-xs pull-right') %>

We can now safely remove the <p> </p> tags and have the final block:

<% if current_user == c.user %>
  <%= link_to("Edit", edit_case_path(c), class: 'btn btn-default btn-xs pull-right') %>
  <%= link_to("Delete", case_path(c), method: :delete, class: 'btn btn-danger 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!link_to

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_case_path(c), class: 'btn btn-default btn-xs pull-right') do %>
    Edit
  <% end %>
  <%= link_to(case_path(c), 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_case_path(c), class: 'btn btn-default btn-xs pull-right') do %>
    <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span> Edit
  <% end %>
  <%= link_to(case_path(c), method: :delete, class: 'btn btn-danger btn-xs pull-right') do %>
    <span class="glyphicon glyphicon-trash" aria-hidden="true"></span> Delete
  <% end %>

Done!

results matching ""

    No results matching ""