8 use Drupal\Core\Block\BlockPluginInterface;
9 use Drupal\Core\Cache\Cache;
12 * Implements hook_block_alter().
14 function block_test_block_alter(&$block_info) {
15 if (\Drupal::state()->get('block_test_info_alter') && isset($block_info['test_block_instantiation'])) {
16 $block_info['test_block_instantiation']['category'] = t('Custom category');
21 * Implements hook_block_view_BASE_BLOCK_ID_alter().
23 function block_test_block_view_test_cache_alter(array &$build, BlockPluginInterface $block) {
24 if (\Drupal::state()->get('block_test_view_alter_suffix') !== NULL) {
25 $build['#attributes']['foo'] = 'bar';
27 if (\Drupal::state()->get('block_test_view_alter_append_pre_render_prefix') !== NULL) {
28 $build['#pre_render'][] = 'block_test_pre_render_alter_content';
33 * Implements hook_block_build_BASE_BLOCK_ID_alter().
35 function block_test_block_build_test_cache_alter(array &$build, BlockPluginInterface $block) {
36 // Test altering cache keys, contexts, tags and max-age.
37 if (\Drupal::state()->get('block_test_block_alter_cache_key') !== NULL) {
38 $build['#cache']['keys'][] = \Drupal::state()->get('block_test_block_alter_cache_key');
40 if (\Drupal::state()->get('block_test_block_alter_cache_context') !== NULL) {
41 $build['#cache']['contexts'][] = \Drupal::state()->get('block_test_block_alter_cache_context');
43 if (\Drupal::state()->get('block_test_block_alter_cache_tag') !== NULL) {
44 $build['#cache']['tags'] = Cache::mergeTags($build['#cache']['tags'], [\Drupal::state()->get('block_test_block_alter_cache_tag')]);
46 if (\Drupal::state()->get('block_test_block_alter_cache_max_age') !== NULL) {
47 $build['#cache']['max-age'] = \Drupal::state()->get('block_test_block_alter_cache_max_age');
50 // Test setting #create_placeholder.
51 if (\Drupal::state()->get('block_test_block_alter_create_placeholder') !== NULL) {
52 $build['#create_placeholder'] = \Drupal::state()->get('block_test_block_alter_create_placeholder');
57 * #pre_render callback for a block to alter its content.
59 function block_test_pre_render_alter_content($build) {
60 $build['#prefix'] = 'Hiya!<br>';