I want a variable in menu.html.twig file. I tried adding the following hook in the theme's .theme file, but the template file doesn't print anything.

function my_theme_name_preprocess_menu(&$variables) {
  $account = \Drupal::currentUser();
  $variables['current_username'] = $account->getDisplayName();

The menu.html.twig template file contains the following markup.

<div class="title-container">
   <span class="item-title">{{ current_username }}</span>

1 Answer 1


Two issues. For preprocessing in general, a variable depending on the current user needs also cache metadata:

$variables['current_username'] = [
  '#markup' => \Drupal::currentUser()->getDisplayName(),
  '#cache' => [
    'contexts' => [
    'tags' => [
      'user:' . \Drupal::currentUser()->id(),

Specific to menu templates. They are not normal template files, they contain a macro which is run for each menu item, where only the variables are available which are passed in the argument list:

{% macro menu_links(items, attributes, menu_level) %}

So you need to add the variable in the items menu tree so that it is available for the menu item you want to target.

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.