block_test.module 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. <?php
  2. /**
  3. * @file
  4. * Provide test blocks.
  5. */
  6. use Drupal\Core\Block\BlockPluginInterface;
  7. use Drupal\Core\Cache\Cache;
  8. /**
  9. * Implements hook_block_alter().
  10. */
  11. function block_test_block_alter(&$block_info) {
  12. if (\Drupal::state()->get('block_test_info_alter') && isset($block_info['test_block_instantiation'])) {
  13. $block_info['test_block_instantiation']['category'] = t('Custom category');
  14. }
  15. }
  16. /**
  17. * Implements hook_block_view_BASE_BLOCK_ID_alter().
  18. */
  19. function block_test_block_view_test_cache_alter(array &$build, BlockPluginInterface $block) {
  20. if (\Drupal::state()->get('block_test_view_alter_suffix') !== NULL) {
  21. $build['#attributes']['foo'] = 'bar';
  22. }
  23. if (\Drupal::state()->get('block_test_view_alter_append_pre_render_prefix') !== NULL) {
  24. $build['#pre_render'][] = 'block_test_pre_render_alter_content';
  25. }
  26. }
  27. /**
  28. * Implements hook_block_build_BASE_BLOCK_ID_alter().
  29. */
  30. function block_test_block_build_test_cache_alter(array &$build, BlockPluginInterface $block) {
  31. // Test altering cache keys, contexts, tags and max-age.
  32. if (\Drupal::state()->get('block_test_block_alter_cache_key') !== NULL) {
  33. $build['#cache']['keys'][] = \Drupal::state()->get('block_test_block_alter_cache_key');
  34. }
  35. if (\Drupal::state()->get('block_test_block_alter_cache_context') !== NULL) {
  36. $build['#cache']['contexts'][] = \Drupal::state()->get('block_test_block_alter_cache_context');
  37. }
  38. if (\Drupal::state()->get('block_test_block_alter_cache_tag') !== NULL) {
  39. $build['#cache']['tags'] = Cache::mergeTags($build['#cache']['tags'], [\Drupal::state()->get('block_test_block_alter_cache_tag')]);
  40. }
  41. if (\Drupal::state()->get('block_test_block_alter_cache_max_age') !== NULL) {
  42. $build['#cache']['max-age'] = \Drupal::state()->get('block_test_block_alter_cache_max_age');
  43. }
  44. // Test setting #create_placeholder.
  45. if (\Drupal::state()->get('block_test_block_alter_create_placeholder') !== NULL) {
  46. $build['#create_placeholder'] = \Drupal::state()->get('block_test_block_alter_create_placeholder');
  47. }
  48. }
  49. /**
  50. * #pre_render callback for a block to alter its content.
  51. */
  52. function block_test_pre_render_alter_content($build) {
  53. $build['#prefix'] = 'Hiya!<br>';
  54. return $build;
  55. }