function user_toolbar

Same name and namespace in other branches
  1. 9 core/modules/user/user.module \user_toolbar()
  2. 8.9.x core/modules/user/user.module \user_toolbar()
  3. 10 core/modules/user/user.module \user_toolbar()

Implements hook_toolbar().

File

core/modules/user/user.module, line 1046

Code

function user_toolbar() {
    $user = \Drupal::currentUser();
    $items['user'] = [
        '#type' => 'toolbar_item',
        'tab' => [
            '#type' => 'link',
            '#title' => $user->getDisplayName(),
            '#url' => Url::fromRoute('user.page'),
            '#attributes' => [
                'title' => t('My account'),
                'class' => [
                    'toolbar-icon',
                    'toolbar-icon-user',
                ],
            ],
            '#cache' => [
                // Vary cache for anonymous and authenticated users.
'contexts' => [
                    'user.roles:anonymous',
                ],
            ],
        ],
        'tray' => [
            '#heading' => t('User account actions'),
        ],
        '#weight' => 100,
        '#attached' => [
            'library' => [
                'user/drupal.user.icons',
            ],
        ],
    ];
    if ($user->isAnonymous()) {
        $links = [
            'login' => [
                'title' => t('Log in'),
                'url' => Url::fromRoute('user.page'),
            ],
        ];
        $items['user']['tray']['user_links'] = [
            '#theme' => 'links__toolbar_user',
            '#links' => $links,
            '#attributes' => [
                'class' => [
                    'toolbar-menu',
                ],
            ],
        ];
    }
    else {
        $items['user']['tab']['#title'] = [
            '#lazy_builder' => [
                'user.toolbar_link_builder:renderDisplayName',
                [],
            ],
            '#create_placeholder' => TRUE,
            '#lazy_builder_preview' => [
                // Add a line of whitespace to the placeholder to ensure the icon is
                // positioned in the same place it will be when the lazy loaded content
                // appears.
'#markup' => ' ',
            ],
        ];
        $items['user']['tray']['user_links'] = [
            '#lazy_builder' => [
                'user.toolbar_link_builder:renderToolbarLinks',
                [],
            ],
            '#create_placeholder' => TRUE,
            '#lazy_builder_preview' => [
                '#markup' => '<a href="#" class="toolbar-tray-lazy-placeholder-link">&nbsp;</a>',
            ],
        ];
    }
    return $items;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.