Create the block class file /web/modules/custom/my_module/src/Plugin/Block/HelloBlock.php
and add the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<?php namespace Drupal\my_module\Plugin\Block; use Drupal\Core\Block\Annotation\Block; use Drupal\Core\Block\BlockBase; /** * Provides a 'Hello' Block. * * @Block( * id = "hello_block", * admin_label = @Translation("Hello block"), * category = @Translation("Hello World"), * ) */ class HelloBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { return [ '#markup' => $this->t('Hello, World!'), ]; } } |
To insert this block programmatically in a template we can implement a hook_preprocess into .module file of our module
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<em>/** * Implements hook_preprocess(). */ </em>function my_module_preprocess(&$variables, $hook) { static $hooks; $block_manager = \Drupal::<em>service</em>('plugin.manager.block'); $block_config = []; $block_plugin = $block_manager->createInstance('<code>hello_block</code>', $block_config); $block_build = $block_plugin->build(); $variables['<code>hello_block</code>_output'] = render($block_build); } |
Then into our template file we display the variable
1 |
{{ block_related_cases_output }} |
don’t forget to execute : vendor/bin/drush cr
No comments yet.