Editing question based on information from @NoSssweat
The book module uses the same hook for the book tree block and the rendered index view in the book page.
I have used the below code to return file name suggestions, so that I can override the html output for the book tree block in a specific region - "sidebar-first". I expected the below code would spit out something like book-tree--book-toc-180--sidebar-first.html.twig
. Instead, it just spits out a file name suggestion that is already being suggested:
This file name suggestion is the same for the main content on the book page. How can I target any book tree blocks within the sidebar-first
region?
function uswds_subtheme_preprocess_book_tree__book_toc_180(&$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();
}
}
}
function uswds_subtheme_theme_suggestions_book_tree__book_toc_180_alter(array &$suggestions, array $variables) {
if (isset($variables["attributes"]["region"])) {
$suggestions[] = $variables["theme_hook_original"] . "__" . $variables["attributes"]["region"];
}
}
2nd attempt
I did the below, and it works but it only works for the book module default block, although any other book module block plugin all mostly use book-tree.html.twig
function uswds_subtheme_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();
}
}
}
function uswds_subtheme_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
if (isset($variables["attributes"]["region"])) {
$suggestions[] = $variables["theme_hook_original"] . "__" . $variables["attributes"]["region"];
}
}