Score:0

How can I have a custom block show different content on the front page?

za flag

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.

sonfd avatar
in flag
See [cacheability of render arrays](https://www.drupal.org/docs/8/api/render-api/cacheability-of-render-arrays) on drupal.org.
Score:1
vg flag

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.

za flag
Thanks @remy, I did end up using caching based on that other post. That was the ticket.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.