Block Caching “Gotcha” in Drupal 8
I recently had a fight with the Block system in Drupal 8. To be brief, if you’re trying to disable caching on a block, make sure to set the #cache element regardless of whether the block has output or not.
This does not work (empty result gets cached):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
/** * {@inheritdoc} */ public function build() { $output = []; $user_id = \Drupal::routeMatch()->getRawParameter('user'); $current_user_id = \Drupal::currentUser()->id(); if ($user_id == $current_user_id) { $output = [ '#theme' => 'item_list', '#list_type' => 'ul', '#items' => [ Link::fromTextAndUrl(t('Edit profile'), Url::fromRoute('entity.user.edit_form', ['user' => $user_id])), Link::fromTextAndUrl(t('Logout'), Url::fromUserInput('/user/logout')), ], '#wrapper-attributes' => ['class' => 'member-utilities'], '#cache' => [ 'max-age' => 0, ], ]; } return $output; } |
This does work (nothing gets cached, as desired):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
/** * {@inheritdoc} */ public function build() { $output = [ '#cache' => [ 'max-age' => 0, ], ]; $user_id = \Drupal::routeMatch()->getRawParameter('user'); $current_user_id = \Drupal::currentUser()->id(); if ($user_id == $current_user_id) { $output['#theme'] = 'item_list'; $output['#list_type'] = 'ul'; $output['#items'] = [ Link::fromTextAndUrl(t('Edit profile'), Url::fromRoute('entity.user.edit_form', ['user' => $user_id])), Link::fromTextAndUrl(t('Logout'), Url::fromUserInput('/user/logout')), ]; } return $output; } |