I've created a custom theme, let's call it "mytheme" in the examples, with the "classy" theme as base. I use several templates, one is menu--account.html.twig, it's an override I made of the classy menu.html.twig template to display a menu. In that template I need the username and some other info from the currently logged in user.

I've tried different ways of getting it to output the username in the template, i.e. the preprocess functions like so:


function mytheme_preprocess(&$variables, $hook, $info) {
  $variables['current_user_name'] = $variables['user']->getDisplayName();
  var_dump($variables['current_user_name']); //ironically this does dump the variable

I've tried using the Bamboo Twig module and get the username like so:

<!-- Get Current User -->
{% set user = bamboo_load_currentuser() %}
<div>{{ user.name.value }}</div>

Both variants don't work for me. If I try to dump the username with

{{ dump(current_user_name) }} or {{ dump(user.name.value) }}

all I get is NULL in the template output. From searching online I'm sure that one of these variants should work, but they don't.

I've also cleared caches several times during the tests, so that can be ruled out too.

Do you have any other suggestions on how to output the variable in that template?


I think that it might work if you do like this,

function mytheme_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['current_user_name'] = $user->getUsername();

Remember to clear the caches.

UPDATE: after lot's of debugging we found out this this code worked, in case any other are running in to the same issue,

function themename_preprocess_menu(&$variables) {
  $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
  $variables['attributes']['uname'] = $user->getUsername();
  • I've tried your proposal, but that crashes the template with the following error: "Error: Class 'User' not found in mytheme_preprocess_menu() (line 4 of themes/mytheme/myheme.theme)." – plocks Oct 10 '18 at 14:25
  • 1
    Ahh I forgot the User namespace, try the updated code. – Jdrupal Oct 10 '18 at 14:27
  • 1
    Try to dump $variables in your php function to make sure your variable is there. – Jdrupal Oct 10 '18 at 14:45
  • 1
    Yeah, the $variables array is probably to large, try dump $variables['current_user_name']. – Jdrupal Oct 10 '18 at 14:51
  • 1
    Let us continue this discussion in chat. – Jdrupal Oct 10 '18 at 14:54

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.