-
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):
1234567891011121314151617181920212223242526/*** {@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):
123456789101112131415161718192021222324/*** {@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;} -
Passing Arguments to Drupal Blocks
You can pass any number of arguments to a Drupal block by providing default arguments. The screenshot below shows what an argument might look like in Views2.
-
Using module_list() to show active Drupal modules
This code can be used in a custom module, a template.php file, or most easily in a block. This looks good in the header bar on a demo site, without a title, as you can see in the screenshot! The reason I am using this is because I do a lot of Drupal demos and it’s great to have the active modules showing so there is no question of what’s required to do whatever it is I am showing. The list of modules is ordered by weight, then filename, which makes it easy to determine if your custom modules are running at the right times.
12345<?php$modules = implode(', ', module_list());print '<font style="font-size: 9px; line-height: 18px;">';print "<strong>Active Modules: </strong>{$modules}</font>";?>Screenshot of the block displayed in the sites header region: