0

I've got a custom block plugin which has some configuration settings that can set from the block configuration form. How can I then access that configuration info later when the block is being rendered? I know that if I know the block's instance id, I can get the configuration data using:

\Drupal::config('blockID'])->getRawData()

However, I'm having trouble finding a hook that can determine the block instance id at the same level as the template so that it can pass that data as a TWIG variable.

I can find the block id inside of HOOK_preprocess_block(&$variables), but then I don't know how to pass anything from this hook to the theme template.

Vice versa, if i use HOOK_preprocess_TEMPLATE(&$variables), I cannot figure out how to get the block instance id in order to pull the configuration values.

I know what the default block id is and can hard code that into the theme template hook, however, this breaks down if more than one instance of the block is placed into the site. What is the right approach to retrieving block instance configuration settings for use in the theme TWIG template?

1 Answer 1

0

Thanks to Jaypan over at the Drupal forums who provided the answer to this issue, in a post regarding a different config form question. The proper way to pass config data to the theme template is to define variables in the template registration, in the theme's hook function. Then in the block plugin class definition's build() function we can populate those variables with values from the configuration.

In theme's hook_theme() function, register the template with variables to be passed to the template.

/**
 * Implements hook_theme().
 */
function hook_theme() {
  return [
    // The theme key.
    'bubblepop' => [
      // The variables used in the render array.
      'vars' => [
        'color' => NULL,
        'text' => NULL,
      ],
      // I believe this must be the same as the theme key, with any
      // underscores turned into hyphens.
      'template' => 'bubblepop',
    ],
  ];
}

In the block's build function we can then populate them with config values:

public function build() {
  $config = $this->getConfiguration();
  return [
    // An arbitrary theme, defined in hook_theme().
    '#theme' => 'bubblepop',
    // Attributes are defined in hook_theme().
    '#color' => $config['color'],
    '#text' => $config['text'],
  ];
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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