Pass variables to template using hook_block_view_alter() I'm trying the change the homepage path based on the current request. The system_main_block block renders the logo which is linked to the homepage. If the current path starts with /foo/..., I want to change the homepage path to point to /foo instead of the default /.

I want to pass a custom variable to a block using hook_block_view_alter().

The hook gives me the build array and the Block itself as arguments.

How can I add a variable to the build array that I can then access in the view (twig template)?

The build array looks like this:

array
    '#theme' =&gt; string 'block'
    '#attributes' =&gt; 
        array (size=0)
        empty
    '#contextual_links' =&gt; 
        ...
    '#weight' =&gt; int -3
    '#configuration' =&gt; 
        array (size=4)
            'id' =&gt; string 'system_main_block' (length=17)
            'label' =&gt; string 'Main page content' (length=17)
            'provider' =&gt; string 'system' (length=6)
            'label_display' =&gt; string '0' (length=1)
    '#plugin_id' =&gt; string 'system_main_block' (length=17)
    '#base_plugin_id' =&gt; string 'system_main_block' (length=17)
    '#derivative_plugin_id' =&gt; null
    '#id' =&gt; string 'my_id' (length=19)
    '#pre_render' =&gt; 
        array (size=1)
            0 =&gt; string 'Drupal\block\BlockViewBuilder::preRender' (length=40)
    '#block' =&gt; 
        object(Drupal\block\Entity\Block)[3592]


I can't see where I can assign an extra variable. Am using the wrong hook?
I think a better option is to override PathProcessorFront::processOutbound():

 public function processOutbound($path, &amp;$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
    // The special path '&lt;front&gt;' links to the default front page.
    if ($path === '/&lt;front&gt;') {
      $path = '/';
    }
    return $path;


Overriding in this case means using a similar outbound pathprocessor with a higher priority and replace '/&lt;front&gt;' or a lower priority and replace '/'.

Edit:

Register the path processor as a service with the tag path_processor_outbound in mymodule.services.yml. This is the core service definition from the example before:

path_processor_front:
    class: Drupal\Core\PathProcessor\PathProcessorFront
    tags:
      - { name: path_processor_inbound, priority: 200 }
      - { name: path_processor_outbound, priority: 200 }
    arguments: ['@config.factory']