2

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

<?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' => $this->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()->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' => $this->t('This is just a text initially'),

I could have a template somewhere:

<div>
  <p>This is a great example</p>
</div>

and then return the template in the build function.

How can I return a template inside the build method of my block?

2

In your modules *.module file you must implement hook_theme() like this:

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

Then you can return this in your block:

$test = 'My custom variable';
return [
  '#theme' => 'fax_custom_theme',
  '#test' => $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.

  • Comments have been deleted. Please don't use them for a continuous back-and-forth. That is not the purpose of comments. – kiamlaluno Sep 13 at 11:57

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.