0

I have a custom module, in Drupal 9, (showing a block in a region) that has an admin form with a checkbox for showing only on the "front page" or if unchecked on "all" pages.

In order for the block to show on the homepage or on all pages do I need some sort of preprocess function to run before the block loads? Does the build() only happen once and then is cached? If so, how do we let the block know what page it belongs on programmatically?

I have a simple build function to test this (build() is inside src/plugin/block), which doesn't work:

 public function build(){
        $alert_front = \Drupal::config('alert_front.settings')->get('front');
        $current_is_front = \Drupal::service('path.matcher')->isFrontPage();
    
      if ($current_is_front) {
        return [
          '#markup' => $this->t("Yes, Front Page Only"),
        ];
      }else{
       return [
        '#markup' => $this->t('@alert and @fp',[
          '@alert' => alertType($alert_type),
          '@fp' => $alert_front,
        ]),
       ];
     }
}

The Drupal block api isn't giving me much here, but I'll keep digging. Thanks for any ideas.

1

1 Answer 1

1

Usually you restrict a block to a Content Type, Pages or Roles (or a mix of them) when placing the block in the block edit dialog - see https://www.drupal.org/docs/core-modules-and-themes/core-modules/block-module/managing-blocks

Still, this will not handle caching for your dynamic block content.

If you want to make this "switch" in your build method, you definitely need to think about caching yourself, see fe. this answer from @Berdir https://drupal.stackexchange.com/a/199601/3218

You could use the url.path.is_front context - see https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts for more information

Maybe splitting your block into two different blocks will make it easier and clearer.

1
  • Thanks @remy, I did end up using caching based on that other post. That was the ticket. Sep 2, 2021 at 0:15

Your Answer

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

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