Problem/Motivation
I'm trying to follow the documentation for creating a "custom block" via a block plugin here:
https://www.drupal.org/docs/creating-custom-modules/creating-custom-bloc... β
The problem arises when we try to create a custom template for the block:
https://www.drupal.org/docs/creating-custom-modules/creating-custom-bloc... β
I've started a discussion on that page, but it hasn't gone anywhere. Hoping this issue will get more eyes.
The problem is that if you follow that documentation, you end up with unnecessary nested block templates.
Your markup will look something like this:
<div class=block block-id--my-block">
<h2 class="block__title">My Block</h2>
<div class="block__content">
<div class="block">
<div class="block__content">
// Content here
</div>
</div>
</div>
</div>
When ideally it would look like this:
<div class=block block-id--my-block">
<h2 class="block__title">My Block</h2>
<div class="block__content">
// Content here
</div>
</div>
Steps to reproduce
Follow this documentation:
https://www.drupal.org/docs/creating-custom-modules/creating-custom-bloc... β
Proposed resolution
I have an alternative suggestion, but it has its own unwanted side effects.
MyBlock.php
/**
* @Block(
* id = "my_block",
* admin_label = @Translation("My Block"),
* )
*/
class MyBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return [
'#theme' => 'block__my_block',
];
}
}
my_module.module
/**
* Implements hook_theme().
*/
function my_module_theme($existing, $type, $theme, $path) {
return [
'block__my_block' => [
// @todo: If default 'content' variable is provided contextual
// links will not render in Layout Builder.
'variables' => [],
'template' => 'my-block',
'path' => $path . '/templates/block',
'base hook' => 'block'
],
]
}
The problem with this solution is that passing any value for variables['content']
in my_module_theme()
causes contextual links to not render when the block is placed via Layout Builder (and I assume when the block is placed via Block Layout).
Remaining tasks
Document a process for creating a custom block via a block plugin and a corresponding template in a module that does not generate unnecessary markup and also allows contextual links to render.
User interface changes
API changes
Data model changes
Release notes snippet