A Pattern for Drupal 8 Blocks

For Drupal 7, I have a pattern to help simplify creating and managing custom blocks for a site. Since the standard hook_block_info() and really hook_block_view() implementations tend to get messy and junked up with markup in the code.  My solution was the use the block delta key from the block info array as a helper function name called from the hook_block_view(), and a theme function in hook_theme() to make sure I could easily create a template for each block. I’m not going into detail about it since was hardly original and I’ve seen several variations from other developers.

When I started to work on Drupal 8 I wanted to develop a similar pattern to help create simple conventions for integration with front end work on a project. While the new plugin system helps avoid the ugliness of old hook_block_view() implementations, how to create a twig file for your custom block isn’t obvious and doesn’t impose a naming convention. Worse, I’ve seen lots of example code with blocks that return render arrays of type markup meaning they have HTML in strings in PHP.

Most projects involve a collection of nearly static blocks that provide basic information like the copyright information, a disclaimer text, a link to the firm that built the site, decorative flourishes, and other similar elements that don’t benefit from being managed as content. After a couple experiments I’ve come up with a solution that works pretty well:

Outline of the custom blocks pattern.
  1. Create a module for simple blocks (although I use the rest of the pattern anytime I’m creating a custom block).
  2. Create the block class for each block.
  3. Create a theme function for each block.
  4. Create a twig file to implement the theme function.

The for a copyright block the class itself is simple.  We implement the variables we want rendered by the block, and set the cache to expire at midnight (one of the places a timed cache makes more sense that cache tags):

With the block created, we need to define the custom_blocks_copyright theme function we included in the block using hook_theme() from within the dot module file.  Remember any custom variables you used in the block class need to also be defined here (in this case attributes and year):

Finally, create the twig file to provide the actual markup.

Leave a Reply

Your email address will not be published. Required fields are marked *