How do I return a Twig template inside the build method of a block class? Am new to Drupal and this week I learned quite a bit about module development, and for today the case is:

For my new module, I create a custom block that renders a markup, and from the folder structure, the class looks like this:

Note: fax is the module's machine name.

fax/src/Plugin/Block/FaxBlock.php

&lt;?php
namespace Drupal\fax\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Cache\Cache;

/**
 * Provides a 'Fax' block.
 *
 * @Block(
 *   id = "fax_block",
 *   admin_label = @Translation("Fax block"),
 * )
 */
class FaxBlock extends BlockBase implements BlockPluginInterface {

    public function build() {

        return array(
            '#markup' =&gt; $this-&gt;t('This is just a text initially'),
        );  
    }

}


I know that in the build method we can also return a form for instance:

 public function build() {
    return \Drupal::formBuilder()-&gt;getForm('Drupal\rsvplist\Form\RSVPForm');
 }


And that we can put HTML inside the array if we want.

Question: how can I instead create a template a return that inside the array?

so, instead of returning a markup like this:

'#markup' =&gt; $this-&gt;t('This is just a text initially'),


I could have a template somewhere:

&lt;div&gt;
  &lt;p&gt;This is a great example&lt;/p&gt;
&lt;/div&gt;


and then return the template in the build function.

How can I return a template inside the build method of my block?
In your modules *.module file you must implement hook_theme() like this:

/**
 * Implements hook_theme().
 */
function fax_theme() {
  return [
    'fax_custom_theme' =&gt; [
      'variables' =&gt; [
        'test' =&gt; NULL, # Makes the {{ test }} variable available in the template.
      ],
    ],
  ];
}


Then you can return this in your block:

$test = 'My custom variable';
return [
  '#theme' =&gt; 'fax_custom_theme',
  '#test' =&gt; $test, # Assigns a value to the {{ test }} variable.
];


This makes the {{ test }} variable available in your theme.

Then add your template to the module under fax/templates/fax-custom-theme.html.twig.

Template names are using dashes instead of undercores.