Last active
October 6, 2016 10:59
-
-
Save waako/254ba133d2fa599800b25d9c06caf368 to your computer and use it in GitHub Desktop.
Drupal 8 Block and Menu template suggestions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_theme_suggestions_HOOK_alter(). | |
*/ | |
function THEMENAME_theme_suggestions_block_alter(array &$suggestions, array $variables) { | |
$block_id = $variables['elements']['#id']; | |
// See if block ID contains the word mobile. | |
$is_mobile_block = strpos($block_id, 'mobile'); | |
$block = \Drupal\block\Entity\Block::load($block_id); | |
$region = $block->getRegion(); | |
// Check if block ID contains the word 'mobile' then define a common template. | |
if ($is_mobile_block !== false) { | |
$suggestions[] = 'block__' . $region . '__mobile_menus'; | |
} | |
} | |
/** | |
* Implements hook_preprocess_HOOK() for block.html.twig. | |
*/ | |
function THEMENAME_preprocess_block(&$variables) { | |
// Add a clearfix class to system branding blocks. | |
if ($variables['plugin_id'] == 'system_branding_block') { | |
$variables['attributes']['class'][] = 'clearfix'; | |
} | |
// Add the block ID as custom attribute to block content, this will be used | |
// for menu template suggestions. | |
$variables['content']['#attributes']['block'] = $variables['elements']['#id']; | |
} | |
/** | |
* Implements hook_theme_suggestions_HOOK_alter(). | |
*/ | |
function THEMENAME_theme_suggestions_menu_alter(array &$suggestions, array $variables) { | |
$menu_name = $variables['menu_name']; | |
$is_mobile_menu = strpos($menu_name, 'mobile'); | |
if (isset($variables['attributes']['block'])) { | |
$block = \Drupal\block\Entity\Block::load($variables['attributes']['block']); | |
$region = $block->getRegion(); | |
$suggestions[] = 'menu__' . $region . '__' . $menu_name; | |
} | |
// If menu name contains the word mobile, create common template suggestion. | |
if ((isset($variables['attributes']['block'])) && ($is_mobile_menu !== false)) { | |
$suggestions[] = 'menu__' . $region . '__mobile-menus'; | |
} | |
} | |
/** | |
* Implements hook_preprocess_HOOK() for menu.html.twig. | |
*/ | |
function THEMENAME_preprocess_menu(&$variables) { | |
$menu_name = $variables['menu_name']; | |
$is_mobile_menu = strpos($menu_name, 'mobile'); | |
if ($is_mobile_menu !== false) { | |
$variables['attributes']['class'][] = 'mobile-menu'; | |
} | |
$variables['attributes']['class'][] = 'clearfix'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment