1

$account->getDisplayName() Bypasses "username" Field Preprocessing in User Template?

I am trying to print the value of the username field of the user account in a user--custom.html.twig file.

MYMODULE.module:

function hook_preprocess_user(&$variables) {
  $account = $variables['elements']['#user'];
  $variables['userName'] = $account->getDisplayName();
}

user--custom.html.twig:

{{ user.name.0.value }}

Both the above examples access the username, but seem to access the value directly and circumvent any preprocessing of the username field (e.g. hook_preprocess_username()), so it looks like I need a different approach.

I have a view that shows the "User" entity so does not use fields and relies on the user template. What am I missing when trying to get the processed value of the username field, instead of the user name DB value for the account?

Related: Get username in custom user twig template but different.

In my template, I am rendering content.user_picture and trying to render username. So maybe I need to load the user instead of both fields? Looking for the processed username field value.

1 Answer 1

0

You're probably looking for the username theme:

$variables['userName'] = [
  '#theme' => 'username',
  '#account' => $account,
];

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.