2

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.

2

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".

1
  • Works perfectly! Thanks you
    – JFK
    Nov 26 '21 at 22:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.