Render an HTML element before the menu with hook preprocess menu I want to render an HTML element like &lt;span&gt;This is my menu&lt;/span&gt; before my menu. I thought the most easy solution is to alter the menu. I already altered my menu to add a class. But how do I add an element before my menu with a hook preprocess function?

I know I can extend menu.html.twig to menu--my-mwnu.html.twig and add it there but I think it's less overhead to add it with a preprocess function.

/**
 * Implements hook_preprocess_menu().
 */
function mytheme_theme_preprocess_menu(&amp;$variables) {

  if (isset($variables['menu_name'])) {
    if ($variables['menu_name'] === 'my-menu') {

      $variables['attributes']['class'][] = 'my-menu';
    }
  }
}
In this case you should edit the template. Changes to markup should be done in templates.


  Ok thank you. I will extend the twig file. But just to know. How do I add it within my preprocess function?


Looking into the standard menu.html.twig there isn't any place left to preprocess content to have it prefixed with some markup for example. There are just menu items that must be of type URL and attributes.

So your best bet probably is to add the markup to the block instead (in case you print your menu in a block).

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_block__footermenu(&amp;$variables) {
  $variables['content']['#prefix'] = '&lt;span&gt;This is my menu&lt;/span&gt;';
}