Drupal 9 how to pass arguments to custom blocks

To pass arguments to custom blocks in Drupal 9, you can follow these steps:

  1. Define the block class:
namespace Drupal\your_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;

/
 * Provides a custom block with arguments.
 *
 * @Block(
 *   id = "your_module_custom_block",
 *   admin_label = @Translation("Custom Block"),
 *   category = @Translation("Custom Blocks"),
 * )
 */
class CustomBlock extends BlockBase {
  // Your code here
}
  1. Add a constructor to the block class to receive the arguments:
/
 * {@inheritdoc}
 */
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
  parent::__construct($configuration, $plugin_id, $plugin_definition);

  // Your code here
}
  1. Configure the block to accept arguments in the annotation of the block class:
/
 * Provides a custom block with arguments.
 *
 * @Block(
 *   id = "your_module_custom_block",
 *   admin_label = @Translation("Custom Block"),
 *   category = @Translation("Custom Blocks"),
 *   context = {
 *     "arg1" = @ContextDefinition("string"),
 *     "arg2" = @ContextDefinition("string")
 *   }
 * )
 */
  1. Use the arguments in the block's build method:
/
 * {@inheritdoc}
 */
public function build() {
  $arg1 = $this->getContextValue('arg1');
  $arg2 = $this->getContextValue('arg2');

  // Your code here

  return [
    // Your block content here
  ];
}
  1. Place the block with arguments in a region of your theme or layout, and provide the arguments in the block configuration.

By following these steps, you should be able to pass arguments to custom blocks in Drupal 9.