Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Scaling block output as Twig variables in Drupal 8

Parent Feed: 

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.

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