Get the current user in drupal 8 | Drupal 8

Get the current user in drupal 8

Submitted by editor on Wed, 12/02/2015 - 13:36
Question
  • How to get the current user, user ID, user data on drupal 8 ?
  • How To check if the current page is the homepage of Drupal 8 ?

Example:

    //use Drupal\user\Entity\User;
    $userCurrent = \Drupal::currentUser();
    $user = \Drupal\user\Entity\User::load($userCurrent->id());
    $name = $user->getUsername();

 

How To check if the current page is the homepage in Drupal 8

As drupal_is_front_page() on drupal 7, you can use path.matcher service of drupal 8.
Example:
$is_front_page = \Drupal::service('path.matcher')->isFrontPage();

Comments

For that, use a custom module like here
Example : (Custom page)

return array(
      '#theme' => 'tour_custon_theme',
      '#user' => $user,
    );

//OR with inline template
return array(
      '#type' => 'inline_template',
      '#template' => '{{ user }}',
      '#context' => array(
        'user' => $user,
      ),
    );

If you can't do this, try to use the hook template_preprocess like:

function template_preprocess_YOURTEMPLATE(&$variables) {
}

Add new comment