4

Is there a way to get the currently logged in user's username as a variable to use in any twig template?

8

You would have to target a specific one. All twig templates is not possible because of caching. Many page elements don't get rebuilt on every request and they will display the wrong user.

And if you try to remove caching from all elements, your site would be very slow.

If you add this to a specific twig template, then you can adjust the cache context of this render element:

function MYTHEME_preprocess_HOOK(&$variables) {
  $variables['currentusername'] = \Drupal::currentUser()->getUsername();
  $variables['#cache']['contexts'][] = 'user';
}

Where HOOK is your template type.

1
  • This works great! Thank you for the implementation details. Aug 2 '16 at 15:09

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.