To check in twig if the user is authenticated you can use the default variable logged_in
:
{% if logged_in %}
<p>The user is authenticated".</p>
{% endif %}
This works because the user module provides the variable in preprocess for all templates:
/**
* Implements hook_template_preprocess_default_variables_alter().
*
* @see user_user_login()
* @see user_user_logout()
*/
function user_template_preprocess_default_variables_alter(&$variables) {
$user = \Drupal::currentUser();
$variables['user'] = clone $user;
// Remove password and session IDs, since themes should not need nor see them.
unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);
$variables['is_admin'] = $user->hasPermission('access administration pages');
$variables['logged_in'] = $user->isAuthenticated();
}
Generic roles
If you want to check a generic role, you can't use hasRole()
, because this method is not available for accounts. You would have to use getRoles()
and check if the role is in the returned array:
{% if 'example_role' in user.getroles %}
<p>The user has the role "example_role".</p>
{% endif %}
Drupal 10.1.x
You can use hasRole()
now. See the change record https://www.drupal.org/node/3002289.