I have a twig template for the compact display of a user where I am able to output the defined content fields. Is there a way to output the username of that user?


{{ user.name.0.value }}

should give you what you want.

The preferred way is inject the username as a variable in a preprocess function. To do so, tweak that in your theme's .theme file


 * Implements hook_preprocess_user().
function yourtheme_preprocess_user(&$variables) {
  /** @var User $account */
  $account = $variables['elements']['#user'];

  $variables['username'] = $account->getDisplayName();

then in your user template you can use that as {{ username }}.


To get the full URL:

  • In your template {{ path('entity.user.canonical', {'user': user.id}, {}) }}
  • In yourtheme_preprocess_user(): $variables['user_url'] = Url::fromRoute('entity.user.canonical', ['user' => $account->id()])->setAbsolute()->toString();
| improve this answer | |
  • 2
    The later is preferred so that hook_user_format_name() runs to do anything that a site may want for usernames. – mpdonadio Aug 5 '16 at 13:22
  • Can the full URL of the user page be retreived in a similar way using the user preprocess? – cheesetriple Aug 5 '16 at 15:10
  • Updated response to include 2 methods to get the user page url – zerolab Aug 5 '16 at 15:44
  • Thanks so much for your help. The template method works fine, but the preprocess gives me the following error: Recoverable fatal error: Object of class Drupal\Core\Field\FieldItemList could not be converted to string in Drupal\Core\Routing\UrlGenerator->doGenerate() (line 192 of core/lib/Drupal/Core/Routing/UrlGenerator.php). – cheesetriple Aug 5 '16 at 16:02

The display name is not a field you can configure in {{ content }}. You can get it directly from the user entity:

{{ user.displayname }}

Reference for the php method: AccountInterface::getDisplayName

| improve this answer | |
  • 1
    Should have more votes IMO. This is the equivalent of the preprocess function in the accepted answer but called from the Twig template. – Cottser Sep 9 '19 at 15:41
  • Definitely the best solution. – mrlexington Apr 4 at 20:44

This answer is specifically for getting the username in menu.html.twig

The solution of passing the username through macro worked for me. Setting a variable and passing it into the macro is needed as these are out of scope of the macro in menu.html.twig

{% set username = user.account.name %}
{{ menus.menu_links(items, attributes, 0,logged_in,username) }}
{% macro menu_links(items, attributes, menu_level,logged_in,username) %}
{{ username }}
{% endmacro %}
| improve this answer | |

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.