Skip to content

How To: Add sign_in, sign_out, and sign_up links to your layout template

Justin Holm edited this page May 26, 2019 · 4 revisions

First add sign_in/out links, so the appropriate one will show up depending on whether the user is already signed in:

# views/devise/menu/_login_items.html.erb
<% if user_signed_in? %>
  <li>
  <%= link_to('Logout', destroy_user_session_path, method: :delete) %>        
  </li>
<% else %>
  <li>
  <%= link_to('Login', new_user_session_path) %>  
  </li>
<% end %>

The method: :delete part is required if you use the default HTTP method. To change it, you will need to tell Devise this:

# config/initializers/devise.rb
  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :get

You can then omit method: :delete on all your sign_out links.

Next come the sign_up links. Again, these can be substituted with something else useful if the user is already signed in:

# views/devise/menu/_registration_items.html.erb
<% if user_signed_in? %>
  <li>
  <%= link_to('Edit registration', edit_user_registration_path) %>
  </li>
<% else %>
  <li>
  <%= link_to('Register', new_user_registration_path) %>
  </li>
<% end %>

Then use these templates in your layouts/application.html.erb, like this:

# layouts/application.html.erb
<ul class="hmenu">
  <%= render 'devise/menu/registration_items' %>
  <%= render 'devise/menu/login_items' %>
</ul>
<%= yield %>

Add some menu styling to the CSS (here for a horizontal menu):

ul.hmenu {
  list-style: none;	
  margin: 0 0 2em;
  padding: 0;
}

ul.hmenu li {
  display: inline;  
}
Clone this wiki locally
You can’t perform that action at this time.