Skip to content

Instantly share code, notes, and snippets.

@jasonday
Last active November 15, 2021 15:22
Show Gist options
  • Save jasonday/641f5ba148d3ece0a6339eab5f715b3d to your computer and use it in GitHub Desktop.
Save jasonday/641f5ba148d3ece0a6339eab5f715b3d to your computer and use it in GitHub Desktop.
Drupal 8 Book module tree add region name to FILE NAME SUGGESTIONS
<!-- FILE NAME SUGGESTIONS:
   * book-tree--book-toc-180.html.twig
   * book-tree--book-toc-180--sidebar-first.html.twig
   x book-tree.html.twig
-->
  • The second suggestion is the new suggestion based on what region the block is placed in
  • This allows for targeted templates based on block placement
// Add to your subtheme .theme file
// Replace 'THEMENAME'
// Add a region variable to a block.
function THEMENAME_preprocess_block(&$variables) {
if (isset($variables["elements"]["#id"])) {
$block_id = $variables["elements"]["#id"];
$block = \Drupal\block\Entity\Block::load($block_id);
if ($block) {
$variables["content"]["#attributes"]["region"] = $block->getRegion();
}
}
}
// add a template suggestion based on region name
function THEMENAME_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
if (isset($variables["attributes"]["region"])) {
$suggestions[] = $variables["theme_hook_original"] . "__" . $variables["attributes"]["region"];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment