Join

Main navigation

How to create custom blocks in D8 and set display in Twig

The idea of Drupal 8 is to avoid writing HTML directly in PHP code when making a custom module. In this example, we will show you how to create a custom block programmatically, create a custom Twig file and render desired variables to a template.

20Mar2017

Josip

Javascript Developer

Tags

Drupal 8

Planet Drupal

How-to

Share

The idea of Drupal 8 is to avoid writing HTML directly in PHP code when making a custom module. In this example, we will show you how to create a custom block programmatically, create a custom Twig file and render desired variables to a template.

Follow the next steps:

Create your custom .module file if you don't have one and add hook_theme() with defined variables names, and Twig template name.

Next step is to create a block file and place the code. Go to your custom module folder, open /src/Plugin/Block/ and create file e.g. WSCustom.php. Include some core functions and build your custom block. Define id for your block and admin label, so you can easily find it in Structure -> Block layout and place to a region.

Create a class and extend BlockBase. Use build() function and return an array of variables:

Now clear cache and go to Structure -> Block layout. Find your block and place it in the region you want.

Next step is to create Twig file and render variables. In your themes folder open the theme that you use e.g. wstheme and open folder templates/block. Now, create a file block--ws-custom.html.twig (we defined the namespace in the array 'template' in the first example).