Drupal Answers is a question and answer site for Drupal developers and administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question

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.

share|improve this answer
    
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 yesterday
    
Did you clear caches? – Aram Boyajyan yesterday
    
Yes. I uninstalled and reinstalled the module as well. Didnt help. – Bhuvana yesterday
    
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. – Aram Boyajyan yesterday
1  
The code is correct. – Ivan Jaros yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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