8 – Custom Module Show Block on Front Page or on All

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.