0

I have created a custom module that generates a single custom block based on content retrieved from a remote API. The content is currently displayed in a single contiguous block above the main content.

It works great, however, I am now being asked to split up the custom block content on the page. Essentially, I need to move some of the content into a sidebar and some into a smaller block at the top of the page.

The simple way to do this I guess is to create 2-3 custom blocks through the plugin system and then place them in the desired regions I create on the page templates. The problem with this is that each block would be calling out to the remote api so I would go from a single API call to 3 or even more on the same page. The remote API we are using just returns the entire set of content so I would be loading the same thing 3 or more times.

What I would really like to be able to do is keep my existing block class (in whatever form) and pass that same single API call to 3 seperate templates that can be placed as three separate blocks.

How do I do this?

Alternatively, is is there some way to generate the API call through a function in the .theme file in my theme (abandoning my custom module completely) and then just pass the variables directly to the page rather than going through the block system? I could also live with that though i am not sure how to do it.

3

What I would really like to be able to do is keep my existing block class (in whatever form) and pass that same single API call to 3 seperate templates that can be placed as three separate blocks. How do I do this?

This is possible. Add a configuration option to the block class in blockForm() and then use this option in build() to change the content and template. Then place the block three times and choose for each instance a different option. To avoid calling the remote API three times in one request use drupal_static().

Alternatively, is is there some way to generate the API call through a function in the .theme file in my theme (abandoning my custom module completely) and then just pass the variables directly to the page rather than going through the block system?

This is no problem. You can put three variables in mytheme_preprocess_page() and use them directly in page.html.twig.

Think about caching. You can cache the remote API call with \Drupal::cache('data')->set() with a certain expire time. In a block this is not necessary, you can set a cache max-age and as long the block stays in the cache the remote API is not called.

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.