I've created several block plugins each with their own block form. My goal is to make it so you can select what template to use based on a field in the blockForm. I understand that I can change a block template within the build function by specifying the '#theme' but that refers to the content. I want to change block.html.twig template being used that surrounds the content. I also understand that I can specify the block template by using the naming scheme like block--block-name.html.twig but I want to be able to select the template within a preprocess function. Below is my attempt.
In mytheme.theme I have
function mytheme_theme($existing,$type,$theme,$path){
return [
'wide_grid_block' => [
'variables' => [
'test' => 'Test default value',
],
]
];
}
function mytheme_preprocess_block(&$vars){
$vars['#theme'] = 'wide_grid_block';
}
and in templates/block/wide-grid-block.html.twig I have
Testing: {{ test }}
I assumed the what should occur is that every block should use the wide-grid-block.html.twig file. But they're all still using block.html.twig.
How do I specify a custom block template in a preprocess function?
UPDATE: I've also tried using a theme_suggestions_block_alter hook but I get a white screen when attempting to do so
function alltechcom2017_theme_suggestions_block_alter(array &$suggestions, array $variables) {
$suggestions[0]= 'wide_grid_block';
}
And I've tried with and without the [0]
UPDATE 2: I've managed to add to the suggestions by using
$suggestions[] = 'wide_grid_block';
The issue I had before with the white screen was because the file was in the wrong location. So I know drupal can see it, I just need it to be the most desired one in the list of possible templates.
In the debug info I see
<!-- FILE NAME SUGGESTIONS:
* block--product-selector.html.twig
* wide-grid-block.html.twig
x block.html.twig
-->
And I have a block.html.twig and a wide-grid-block.html.twig. Why is it using block.html.twig instead? It's acting as if my file doesn't exist. I looked at this https://sqndr.github.io/d8-theming-guide/theme-hooks-and-theme-hook-suggestions/theme-hook-suggestions.html and it appeared like I was on the right track.
UPDATE 3: I've added
function mytheme_theme($existing,$type,$theme,$path){
return [
'wide_grid_block' => [
'path' => drupal_get_path('theme','mytheme').'/templates',
'template' => 'wide_grid_block',
],
];
}
but still no luck
block__wide_grid
.