Score:-1

How to handle different output for a same block (Caching Problem)?

cn flag

I have a theme which has two different appearance for main menu block, so I wrote a theme suggestion like this:

function MYTHEME_theme_suggestions_menu_alter(array &$suggestions, array $variables) {
  if ($variables['menu_name'] == 'main' and Drupal::service('path.matcher')
  ->isFrontPage()) {
    array_splice($suggestions, 1, 0, 'menu__main__front');
  }
}

so that I can theme main menu for front page in its own manner. The problem raises is about how Drupal caching system behaves about blocks so that when user navigates to other pages it uses the same block output which is produced for the first page. At first I thought that might be theme suggestion problem but then I realized that when I clear the caches it works fine.

Any suggestion for the case when we want a block be output in different manner based on some condition?

ru flag
You need to add that `context` that changes the appeance to the `#cache` array, in your case `url.path`. See [What is the correct way to set cache contexts on custom blocks?](https://drupal.stackexchange.com/questions/223376/what-is-the-correct-way-to-set-cache-contexts-on-custom-blocks)
4uk4 avatar
cn flag
See https://drupal.stackexchange.com/questions/182005/is-front-is-not-available-in-all-templates
Score:0
de flag

Any suggestion for the case when we want a block be output in different manner based on some condition?

You want Cache Contexts: https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts

Cache contexts provide a declarative way to create context-dependent variations of something that needs to be cached.

As hudri has stated, you need a cache context on url.path.

ca flag
In Drupal 8.3.x `url.path.is_front` is available - saves a few database entries. @see https://www.drupal.org/docs/drupal-apis/cache-api/cache-contexts
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.