4

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:

<?php

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?

3

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 cache.

After debugging, we found out this this code worked, in the case somebody runs into the same issue.

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

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.