D8: Variables in template_preprocess_views_view not passed to twig

 

I had a very strange problem wherein I was not able to affect variables being passed to views-view-grid--my_view.html.twig.

function mytheme_preprocess_views_view(&$vars) {
  if ($vars['view']->id() == 'myview') {
    $vars['amaaaazingVar'] = '!';
  }
}

Yet, sadly, there was no amaaaazingVar to be found in views-view-grid--my_view.html.twig when I did {{ kint() }}.

What did I do? I set a breakpoint in the twig template using this methodology and then looked back through to see what preprocess functions were being called by the theme.

And yes... my preprocess function was called. But the variables weren't getting saved. Strange. Why were my variables clobbered?

I ended up in core/lib/Drupal/Core/Theme/ThemeManager.php with a breakpoint in the render function looking at this chunk of code:

if (isset($info['preprocess functions'])) {
      foreach ($info['preprocess functions'] as $preprocessor_function) {
        if (function_exists($preprocessor_function)) {
          $preprocessor_function($variables, $hook, $info);
        }
      }

My breakpoint was getting hit twice, once before mytheme_preprocess_views_view and once after. On the second hit, I discovered that other preprocess functions were being called by inspecting $info['preprocess functions'], and so I added my variable to the function I found:

function mytheme_preprocess_views_view_grid(&$variables, $hook, $info) {
    if ($vars['view']->id() == 'myview') {
    $vars['amaaaazingVar'] = '!';
  }
}

...and now we have amazingVar!!!

Ask me if I know why. Go on. Ask me.

Alright, I'll speculate. Maybe because this is a view of type grid, and I'm using a grid-specific template—views-view-grid--my_view.html.twig—things get fubarred. But that's the what of it now the why of it. Maybe somebody smarter than me can chime in below.

About the Author

Hi. My name is Jeremiah John. I'm a sf/f writer and activist.

I just completed a dystopian science fiction novel. I run a website which I created that connects farms with churches, mosques, and synagogues to buy fresh vegetables directly and distribute them on a sliding scale to those in need.

In 2003, I spent six months in prison for civil disobedience while working to close the School of the Americas, converting to Christianity, as one does, while I was in the clink.