can we change block title using template_preprocess_block? I am having a need to dynamically change the title of a block. Here is what I am trying but no avail. 

function MYMODULE_preprocess_block(&amp;$variables) {

  if ($variables['elements']['#id'] == "views_block__weekly_schedule_all_blocks_block_2") {

    //$variables['elements']['content']['#title']['#markup'] = "Foobar";

    //$variables['elements']['content']['#title'] = 'foibar';
  }
}


Any help is appreciated.
See the block_example.module. It's hook_block_view_alter you can use to do this programmatically. You can probably use it in a *.theme as well.

Source block_example_block_view_alter.

use Drupal\Core\Block\BlockPluginInterface;

function MYMODULE_block_view_alter(array &amp;$build, BlockPluginInterface $block) {

  // We'll search for the string 'uppercase'.
  $definition = $block
    -&gt;getPluginDefinition();
  if (!empty($build['#configuration']['label']) &amp;&amp; mb_strpos($build['#configuration']['label'], 'uppercase') || !empty($definition['subject']) &amp;&amp; mb_strpos($definition['subject'], 'uppercase')) {

    // This will uppercase the block title.
    $build['#configuration']['label'] = mb_strtoupper($build['#configuration']['label']);
  }
}




Most often you find answers to questions like that really fast when you google for Drupal X how to X programmatically or similar.