0

I need to create multiple custom blocks reusing the same template(XXX.html.twig) and associated js file.

This is how I am trying to implement it.

1)Create separate blocks by extending BlockBase

2)Defined a template in MODULE_NAME.module file using hook_theme and declared the variables that can be passed to the template

3)Created the template file(xxxx.html.twig) defined in the theme.

4)Created a custom js file which retrieves data from a url and populates the elements declared in the template file. The custom js file accepts the url as a drupalSettings variable.

5)Defined the custom js file as a library in MODULE_NAME.libraries.yml and attached it to the block in BlockBase. The variables required by the js file are passed from the block using ['#attached']['drupalSettings']

Here is my build method of one of the blocks

 public function build() {
     return [
      '#theme' => 'news_headlines',
      '#table_uniq_id' => 'top_news_headlines_table',
      '#attached' => array(
        'library' =>  array(      
          'custom_cms_blocks/dataTables.dataTablesjs',
          'custom_cms_blocks/news-headlines-library'
        ),
        'drupalSettings' =>  array(   
          'custom_cms_blocks' => array(   
              'top_news_headlines' => array(      
                  'service_url' => 'http://localhost:8181/test_domain/newsheadlines',
                  'table_uniq_id' => 'top_news_headlines_table' 
               ), 
           ),
        ),
      ),
     ]; 
  } 

I have multiple such blocks with the same configuration and only the variables passed to the template and the js file varies.

My logic is not working. The js file is only getting invoked once even though it is attached to multiple blocks.

How do we invoke the custom js library for all the blocks and pass different values for the variables for each block.

  • Make the top_news_headlines or custom_cms_blocks array of arrays and loop through them in your javascript. – user21641 Mar 10 '16 at 11:11
  • That doesnt help since I only want the code to be executed once per block. Not all of it in the same block. – Bhuvana Mar 11 '16 at 3:53

Your Answer

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

Browse other questions tagged or ask your own question.