I am attempting to set a common class if any preface region in my theme appears. I am trying to render this with a variable using set classes = [] in the region template in my theme.

So far I have set a variable in a preprocess region like this:

function gratis_preprocess_region(&$vars) {
  // Check to see if any of the preface regions have content and if so
  // Set a common var for use as a class in the region template.
  if (!empty($vars['page']['preface_first']) || !empty($vars['page']['preface_second']) || !empty($vars['page']['preface_third'])) {
    $vars['preface_region'] = '';

Then in my theme's region template I attempt to render the variable within the set classes area.

  set classes = [
    'region-' ~ region|clean_class,
    region == preface_region ? 'region-preface'

I am pretty sure I am not doing this the correct way though and it does not work.

  • Sorry I think that I miss something, where is defined $vars['page']? By default there is no $vars['page'] in preprocess_region. If 'preface_first' is a block, maybe you want $vars['elements']['preface_first'].
    – Vagner
    Commented Mar 6, 2016 at 15:06
  • I already get that kind of class for any of the preface regions but I am trying to set a common class if it's any of the three preface regions. Commented Mar 6, 2016 at 15:48

1 Answer 1


It seems the way to do this was to create a theme hook for all preface regions and then it can have its own template. So first I create an alter preprocess function in my theme's .theme file.

function MYTHEME_theme_suggestions_region_alter(&$suggestions, $vars, $hook) {
  // Print the $vars.

  // Define a var for the #region. 
  $preface = $vars['elements']['#region'];

  // Now check for any of the three preface regions and create a theme hook. 
  if ($preface == 'preface_first' || $preface == 'preface_second' || $preface == 'preface_third') {
    $suggestions[] = 'region' .  '__' . 'preface';

Next, voila, when I look at Twig debug, I see a suggestion for my new theme hook.

   * region--preface.html.twig >> **** This is the new template from the alter
   * region--preface-second.html.twig
   x region.html.twig

Now I can create a common template for all three preface regions with region--preface.html.twig.

Then in the new template, I print the classes like so:

set classes = [
'region-' ~ region|clean_class

This gives me exactly what I set out to do and prints this HTML:

<div class="region region-preface region-preface-second">

Now I can use .region-preface for common theming / HTML for any of the three the preface regions.

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.