I am trying to add a variable to render in the menu-account.html.twig file.

Here is my preprocess function in my .theme file.

function HOOK_preprocess_menu__account(&$variables) {
    $variables['account_name'] = Drupal::currentUser()->getAccountName();

HOOK is replaced with my theme name

And in my twig file I have this snippet:

<div class="welcome-message">
    Welcome, {{ account_name }}!

So I can edit pre-existing variables but I cannot seem to add a new one.

I was reading that new variables cannot be added in a preprocess function and that the HOOK_theme_registry_alter should be used.

Here is what I attempted and by using xDebug I can tell that it is getting looked at when flushing caches.

function HOOK_theme_registry_alter(&$theme_registry) {
    $theme_registry['menu']['variables']['account_name'] = [];

Does anyone know the steps to get a new variable to be rendered in the menu twig file. This my first time using the theme registry hook so I might be doing something wrong there as well.


EDIT: "menu--account.html.twig" was named correctly in my code but mistyped in my question. Thank you to GiorgosK for pointing this out.

1 Answer 1


In your THEMENAME.theme

function THEMENAME_preprocess_menu__account(&$variables) {
  $variables['account_name'] = Drupal::currentUser()->getAccountName();

And in your menu--account.html.twig

<div class="welcome-message">
  Welcome, {{ account_name }}!

Just tested and it works, so basically what you posted should work but probably you mistyped the twig file name which needs two dashes (--)

  • Thank you for your reply, that typo was actually just in my question, Checking my code the file is named correctly. (--) Did you have to use the HOOK_theme_registry_alter at all to get this to work? Mar 13, 2018 at 20:02
  • OK, just used what I have above nothing else. Checked with both subtheming bootstrap and classy just to be sure. Maybe start with a clean install and see if you can get it to work.
    – GiorgosK
    Mar 13, 2018 at 20:15
  • 1
    Thank you for your help, I got it working! The issue was actually my lack of understanding the twig template system. My issue was that I was trying to render the {{account_name}} inside of a macro without passing it to the macro first. This is my first d8 project coming from d7. Knowing that I didn't need the registry alter stuff did help me a lot though. Mar 13, 2018 at 20:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.