David Lohmeyer's Blog

Scaling block output as Twig variables in Drupal 8

With Drupal 8's Object Oriented focus, it's just a matter of time before cooler approaches to the theme's giant template.php (now yourtheme.theme) file are found. I've written a nicer way to get block output into the $variables array in page and node preprocess functions. What this allows you to do is use simple variables like {{ my_cool_block_stuff }} in yor Drupal Twig templates.

The source is available on Github. Feel free to take this module and modify it for your project.  This is a great approach if you're designing larger sections and pages and still want granularity on when blocks are rendered, but don't want to overflow the block layout page with a huge number of items. With this you can make a View output a block, but not PLACE the block anywhere. You would then just render the View through this module and the block output would be in a Twig variable for adding to a custom theme template (either a page or node template, see the module for specific code example).

For non views-based blocks, it requires the block to be placed and/or disabled to work.

If you didn't do this you would have a large amount of if statements based on page and node ids to get the same Twig variables. Now, you just add paths or content type conditionals to the switch statements in the module.

Related Posts