0

I am trying to get the Custom Block type fields using a preprocess hook. I can successfully use the following code.

function theme_preprocess_block(&$variables) {
  $content = $variables['elements']['content'];
  if (isset($content['#block_content']) && $content['#block_content'] instanceof BlockContentInterface) {
    $blockType = $content['#block_content']->bundle();

    if ($blockType == 'image_and_video') {
        $variables['title_test'] = $content['#block_content']->get('field_title')->value;
    }
  }
}

Using {{ title_test }} in any of the block templates works well, but I want to use this variable in layout--twocol-section.html.twig for some purpose.

Is there any other way I can use this variable other than the block template?

3
  • Your question is not clear, do you want to use the new variable the same way you use a field in the Layout builder? Jun 17 at 7:00
  • Sorry if it is not clear, I just wanted to know if I can use the preprocess variable globally in any of the templates(block/node/layout, etc). Suppose I am using "preprocess_block", can I use this variable('title_test') in the other templates?? other than block template..
    – user94155
    Jun 17 at 8:24
  • You can use "HOOK_preprocess" to reflect your variable on all templates. In your case, you need to add extra validation to check if the field exists. Personally, I won't recommend using this on a global scale and I prefer a more targeted approach. api.drupal.org/api/drupal/… Jun 17 at 9:55

1 Answer 1

1

$variables['elements']['content']['#block_content'] is not available in other templates, which you can target directly or via the general HOOK_preprocess((&$variables, $hook) and $hook != 'block'. This general hook is only useful for globally available information.

The block entity here is local to the specific block template. A page can have dozens of blocks, each with its own local variables. Blocks are rendered (which includes the execution of preprocess hooks) and then cached, isolated from the rest of the page. Not only in the scope of the variables but also in time. Normally an entity block depends only on the database and unless the database item is not changed it can stay in cache forever.

1
  • Yes, this is the point: Each template receives its own copy of the $variable array. That's why what the OP is trying to achieve is not possible.
    – apaderno
    Jun 17 at 18:56

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.