1

I want to add "Login" and "Logout" to the same menu but only for the right role. In previous versions of Drupal, you would just add /user/login and /user/logout to a menu and it would only render one or the other based on if they actually were logged in or not.

However in D8, it looks like the Logout link shows regardless... is there a way to replicate this without creating multiple menus?

2
  • How does one log out if you hide the Log Out link? How does one login if you hide the Log In link?
    – Joseph
    May 22, 2017 at 18:06
  • Reverse your comment. You see Log out if you are logged in, and vice versa.
    – Kevin
    May 22, 2017 at 18:06

1 Answer 1

1

In D8 this is a menu link class, which you can add to a menu in *.links.menu.yml:

mymodule.links.menu.yml

mymodule.logout:
  weight: 10
  menu_name: mymenu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

This class shows Log in or Log out for user roles authenticated or not:

  public function getTitle() {
    if ($this->currentUser->isAuthenticated()) {
      return $this->t('Log out');
    }
    else {
      return $this->t('Log in');
    }
  }

and links it to the corresponding route:

  public function getRouteName() {
    if ($this->currentUser->isAuthenticated()) {
      return 'user.logout';
    }
    else {
      return 'user.login';
    }
  }
2
  • Hmm, so this is not handled automatically anymore?
    – Kevin
    May 22, 2017 at 18:50
  • You can add menu links in UI for /user/login and /user/logout, and it will show only one of them, because they have defined requirements for the user roles. You can't test this as admin though, because admin has access rights for both.
    – 4uk4
    May 22, 2017 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.