9

I want to restrict a single node to anonymous users in Drupal 8. I don't want to use any module for it as its useless for single restriction as per me.

I know that I can do it with something like this.

{% if user.hasPermission('myPermission') %}
     //my template HTML
{% else %}
    //some login for the customer
{% endif %} 

I don't want to restrict the content via permission, instead I want to restrict it with something like

{% if user.hasRole('authenticated') %}

Is this possible with a theme hook or do I have to use a module?

1 Answer 1

20

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.

6
  • Since the OP is interested in finding out if the user is authenticated, this is the right answer. For a generic role, this would not work.
    – apaderno
    Jan 23, 2017 at 9:13
  • @kiamlaluno, you are right, this would make a more complete answer, I add the code for a generic role
    – 4uk4
    Jan 23, 2017 at 9:23
  • the example with generic roles works like charm. to bad that "getroles" was never listed as i searched for it. thank you very much.
    – Gabbax0r
    Jan 23, 2017 at 9:34
  • I didn't mean the answer was wrong, but it was the one answering the question. Now it is even better, though. I cannot up-vote it since I voted it already, but I would give it a second vote, if I could.
    – apaderno
    Jan 23, 2017 at 16:40
  • @kiamlaluno, didn't see the problem with the limited account interface right away. It was your hint that I digged a bit deeper where the real problem is.
    – 4uk4
    Jan 23, 2017 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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