Add a custom variable to an existing block

mx flag

Is there a way to alter the render array of an existing block? I want to do it for a commerce block (cart block) but the question remains for any core or contrib module block.

When a block uses a custom #theme for it's block, is there a way to alter the definition?

Let's say the module defines the following theme :

 * Implements hook_theme().
function commerce_cart_theme($existing, $type, $theme, $path) {
  return [
    'commerce_cart_block' => [
      'variables' => [
        'icon' => NULL,
        'count' => NULL,
        'count_text' => '',
        'content' => NULL,
        'url' => NULL,
        'links' => [],

and the block uses '#theme' => 'commerce_cart_block' as it's build render array.

I'd like to know if there's a way to add a new custom variable to commerce_cart_block in a hook somewhere.

I tried to rewrite the commerce-cart-block.html.twig in my theme and add a new variable in it and I'd set my variable in THEME_preprocess_block__commerce_cart(), but it doesnt work.

I also tried to alter the block's content with HOOK_block_view_alter in a module, but it also didn't work.

ua flag

You can do it with hook_preprocess_HOOK and the all caps HOOK part refers to the array key in hook_theme().

 * Implements hook_preprocess_HOOK().
function mytheme_preprocess_commerce_cart_block(&$variables) {
  // Adds a custom variable
  $variables['hello_world'] = 'Hello World';

BTW, this hook can be used either in a custom theme or custom module.

and in commerce-cart-block.html.twig

{{ hello_world }}

should print "Hello World".

mx flag
Works perfectly! Thanks you

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.