3

I need to add an option to "User account Menu" that shows the current user name. It is possible to do this using tokens or some other method?

Thanks!

3 Answers 3

2

You can extend LoginLogoutMenuLink and override getTitle()

  public function getTitle() {
    return $this->currentUser->getDisplayName();
  }

and the cache context from role specific to general user:

  public function getCacheContexts() {
    return ['user'];
  }

and use the extended class in mymodule.links.menu.yml:

user.name:
  weight: 10
  menu_name: account
  class: Drupal\mymodule\Plugin\Menu\UserNameMenuLink
4

No, you cannot use tokens in menus out of the box.

Here are some options:

  1. Use Views to create the link. This won't give you a menu, but you can make a block in Views and use that as a menu. You may have to hard-code the rest of your "menu" in the views block, which isn't ideal but if you can't code that may be your best option for now.
  2. Code the menu link. See the routes documentation.
  3. Watch the progress of the Menu Token module. This module does what you want but it doesn't have a stable release for Drupal 8 yet. I haven't used the D8 version so I don't know how well it works at the moment.
-1

With twig_tweak (for twig token filter, tested on 8.x-2.9) you can add a token based link to the user account menu in Drupal 8/9 (/admin/structure/menu/manage/account).

E.g. A menu link:

  • title: [current-user:name]
  • url: /user/[current-user:uid]/edit

Also works with multiple tokens.

  • title: [current-user:name] and [current-user:created]
  • url: /user/[current-user:uid]/edit/[current-user:created]

Note below codes:

  • assumes no extra "[" , "]", or ":" in any parts of the title/link except for token.
  • query params are broken (output as part of the url path)
  • so room for improvement for the tech savvy

twig snippet for menu--account.html.twig.

  • menu.html.twig [drupal]\core\themes\classy\templates\navigation\menu.html.twig)
  • Tokens: @see [drupal]\web\modules\contrib\token\token.tokens.inc
{# CUSTOM START #}
{% if '[' in item.title %}
  {% set item = item|merge({'title': item.title
    |split(']')
    |map(t => drupal_token(t, {'menu-link': item.original_link}) )
    |join
    |replace({
      '[':'',
      ']':'',
    })
  }) %}
{% endif %}
{# Only support internal URLs, being with '/' for now. #}
{% if ('%5B' in item.url.toString()) and (item.url.toString() starts with '\/') %}
  {% set item = item|merge({'url': 'base:' ~ item.url.toString()
    |replace({
      '%5B':'[',
      '%5D':']',
      '%3A':':',
    })
    |split(']')
    |map(t => drupal_token(t, {'menu-link': item.original_link}) )
    |join
    |replace({
      '[':'',
      ']':'',
      ':':'%3A',
    })
  }) %}
{% endif %}
{# CUSTOM END #}

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.