I have a menu with a machine name of menu-principal
, which in turn has a theme hook of menu__menu_principal
and a template of menu--menu-principal.html.twig
. I'm trying to inject another menu into the template in a variable so that I can render it in this menu template but so far have been unsuccessful.
I tried to add a preprocess function to my MY_THEME.theme
but this doesn't seem to work. My code is as follows:
/**
* Implements hook_preprocess_HOOK().
*/
function MYTHEME_preprocess_menu__menu_principal(&$variables) {
$menu_tree_service = \Drupal::service('menu.link_tree');
$menu_name = 'menu-quicklinks';
$menu_parameters = new \Drupal\Core\Menu\MenuTreeParameters();
$tree = $menu_tree_service->load($menu_name, $menu_parameters);
$variables['quicklinks'] = $tree;
}
When I go to to the template and use {{ kint() }}
to dump out the defined variables, I don't see the variable. I only see the following:
I then found this answer and tried the following, using the example from the answer there:
/**
* Implements hook_theme_registry_alter().
*/
function MY_THEME_theme_registry_alter(&$theme_registry) {
$theme_registry['menu__menu_principal']['variables']['quicklinks'] = [];
}
I used dd()
to verify that $theme_registry['menu__menu_principal']['variables']
existed and that the variables were definitely being set in the theme registry, but it still didn't work.
{{ kint () }}
output for it, though, so it does seem to fire. It perhaps just doesn’t do anything.