I am working on a custom slider programmatically. I create a custom module (block_example) and make a block (BlockExample.php) and a twig file (blockexample.html.twig) and also a module file (block_example.module). I want to place some code in twig file and call it in block file.

This is build function from block file (BlockExample.php)

public function build() {

  $renderable = [
    '#theme' => 'blockexample',

  return $renderable;

This is (blockexample.html.twig) file code

<div class="col-sm-3">
  <h1>This is Title</h1>
  <p>Description Coming From Twig File</p>

This is (block_example.module) file code

function block_example_theme() {
  return [
    'block_example' => [
      'variables' => ['test_var' => NULL],

Now main question is how to print twig file in BlockExample.php

  • Why do you want print twig file in BlockExample.php? It's not follow of drupal. In file BlockExample.php you already return a render array, so when you add block in theme content in blockexample.html.twig will be display. – Jonh Jan 27 at 6:49
  • @Jonh – This is totally Drupal. Why build complex markup in a plugin's build function when you can pass all variables to a template and later have others be able to override the markup from their theme? – leymannx Jan 27 at 10:39
  • Muhammad, look: '#theme' => 'blockexample', and return ['block_example' => [. Do you see the difference? One comes with an underscore, and one doesn't. Fix the typo, flush caches a thousand times and tell us if it's working now. – leymannx Jan 27 at 10:45

The theme key you use in you build funtions should be the same with the one you are using in your hook_theme.

In that case you code should look like so

public function build() {

  $renderable = [
    '#theme' => 'block_example',

  return $renderable;

Keep in mind to avoid dashes in those values, since they are used for the template naming.

Best regards.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.