4

In Drupal 8 what is the process for creating blocks with html and javascript?

Here is my sample code for creating the block

class TopNewsBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {
     //Fetch data
     return array(
      'type' => 'markup',
      '#markup' => '<table id="example_table"></table>',
      '#attached' => array(
        'library' =>  array(      
          'custom_cms_blocks/dataTables.dataTablesjs',
          'custom_cms_blocks/top-news-library'
        ),
      ),
     ); 
  } 

}

It works but the problem I have is - I want to seperate out the html code from the php code. Is it possible to include a html file within the block just like the way a javascript file is attached as a library?

1 Answer 1

15

You need to use hook_theme() in your module, and declare a new Twig template that you want to use for your block.

Here's an example that needs to go to YOUR_MODULE.module file:

function YOUR_MODULE_theme() {
  return [
    'YOUR_TEMPLATE_KEY' => [
      // Here you can pass any variables you want, if necessary.
      'variables' => ['var1' => NULL],
    ],
  ];
}

Then create a folder called /templates in your custom module, and YOUR_TEMPLATE_KEY.html.twig file where you can have any markup you want. See below how to use the variables you pass to the template:

<div id="your-block">
  {{ var1 }}
</div>

Finally, to use it:

public function build() {
  return [
    '#theme' => 'YOUR_TEMPLATE_KEY',
    '#var1' => 'Variable one passed here',
  ];
}

Hope this helps.

7
  • I get the error Template "modules/custom/MY_MODULE_NAME/templates/MY_TEMPLATE_NAME.html.twig" is not defined (Drupal\Core\Template\Loader\ThemeRegistryLoader: Unable to find template "modules/custom/MY_MODULE_NAME/templates/MY_TEMPLATE_NAME.html.twig" in the Drupal theme registry.
    – Bhuvana
    Mar 4, 2016 at 11:01
  • Did you clear caches? Mar 4, 2016 at 11:01
  • Yes. I uninstalled and reinstalled the module as well. Didnt help.
    – Bhuvana
    Mar 4, 2016 at 11:02
  • Strange; I tested the code above before posting and it worked well. Make sure that all naming is correct and that there are no typos. Mar 4, 2016 at 11:02
  • 1
    The code is correct.
    – user21641
    Mar 4, 2016 at 12:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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