0

I want to render an HTML element like <span>This is my menu</span> 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(&$variables) {

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

      $variables['attributes']['class'][] = 'my-menu';
    }
  }
}
  • 1
    Why is it less overhead in a preprocess? Performancewise this should not really matter, as both solutions are cached after the first visit. m2c: You should always pick the "least intrusive" method first: CSS -> HTML/Twig -> PHP - If e.g. after an update CSS breaks, your site won't be that beautiful, but stil fully functional. It Twig breaks, your site usually ends up with less rendered output. If PHP breaks, your site often ends up in a WSOD. – Hudri Feb 19 at 9:44
  • 1
    I'm with Hudri. In this case you should edit the template. Since it's a change to the actual markup. Markup = templating. – leymannx Feb 19 at 10:29
  • Ok thank you. I will extend the twig file. But just to know. How do I add it within my preprocess function? – meez Feb 19 at 11:18
1

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(&$variables) {
  $variables['content']['#prefix'] = '<span>This is my menu</span>';
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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