0

My fundamental question is this: in Drupal 8 how can I access block field values in mytheme_preprocess_block.

I am trying to achieve something like https://www.drupal.org/project/block_class_styles in Drupal 8.

So far I have created the block field, and extracted the raw field value in twig (and then add classes or conditional statements) by doing something like:

{{ content.field_layout_style[0]['#markup']|escape }}

This looks really bad, I would rather access this field value in mytheme_preprocess_block, and then pass it to twig, and/or access it in mytheme_theme_suggestions_block_alter and make separate template suggestions based on it.

Help very much appreciated.

  • similar to How to enable template while creating node – No Sssweat Aug 10 '16 at 6:29
  • I think you need to add more detail for us to answer this with accuracy. For example what do you mean by "how it displays", this can mean many things. There are simple modules that allow you to add a class to blocks like drupal.org/project/block_class, right up to advanced modules like Display Suite and Paragraphs. Using a field is of course possible, but some more details are required. – Jeff Burnz Aug 10 '16 at 7:11
  • I will edit the question to be more precise. – piersa Aug 10 '16 at 14:24
1

Here is a code snippet that we use to create block template suggestions based on the block content type (bundle), doing something similar based on a field should be fairly easy (...->yourfield->value):

/**
 * Implements hook_theme_suggestions_HOOK_alter() for block templates.
 */
function ourtheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  if (isset($variables['elements']['content']['#block_content'])) {
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle();
    $suggestions[] = 'block__' . $variables['elements']['content']['#block_content']->bundle() . '__' . $variables['elements']['content']['#view_mode'];
  }
}
|improve this answer|||||
  • Thank you this let me see the wood for the trees - obviously other blocks on the page threw errors because of missing values, so the 'isset' was the thing. Duh! I would still be diving into the big array like : if '(isset($variables['content']['field_layout_style'][0]['#markup'])) { [do stuff] }' which doesn't strike me as very Drupal 8-ish,but if that's all we can access then fine. I will mark as answered and if anyone wants to improve the code then feel free. – piersa Aug 11 '16 at 7:23

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.