D8: Variables in template_preprocess_views_view not passed to twig

Parent Feed: 

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.

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web