0

I have a custom theme (subtheme of drupal bootstrap theme). We are overriding menu--account.html.twig. So I copied menu--account.html.twig from the bootstrap theme template folder into my theme's template folder, and I verified this template is being used because static text changes I added show up on screen.

Now I'm trying to add a variable that the menu--account.html.twig template can read.

How do I do that? My variable's name is 'nickname'. I tried this:

 function mymodule_preprocess_menu__account(&$variables)
 {     
     $variables['nickname'] = 'Jeff';     
 }  

The variable is added to the array, and I can see it if I use dpm, but when I reference {{nickname}} in the template it's always null.

I also read I had to define the variable like this:

 function candidate_poral_theme_registry_alter(&$theme_registry)
 {
   $theme_registry['menu__account']['variables']['nickname'] = 'default';
 }

But that also doesn't work.

Any assistance would be welcome.

2
  • Have to ask, but is your theme registry alter hook spelled correctly? I noticed it says poral instead of portal. Can you verify the code is being hit on cache clear?
    – Kevin
    Commented Oct 25, 2017 at 18:27
  • Well, you're right about the misspelling, but fixing it didn't have any effect other than allowing me to confirm (by dumpign $theme_registry via dsm) that the registry alter hook is being called on a cache clear.
    – jeff.eynon
    Commented Oct 25, 2017 at 19:22

1 Answer 1

1

I have done this for a theme on past projects. Be sure to pass it in through the content item:

Example

use Drupal\Core\Render\Markup;

function mytheme_theme_registry_alter(&$theme_registry) { 
  $theme_registry['menu__account']['variables']['nickname'] = 'default'; 
}

function mytheme_preprocess_menu__account(&$variables) {
  // code...

  $variables['content']['#nickname'] = [
    .. renderable properties
  ];

  // or also...

  $variables['content']['#nickname'] = Markup::create('Jeff');
}

Then, in the twig template:

{{ custom_var }}

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.