Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
I am trying to assign the variables to the return array from the custom controller (block). I have some data in $data array which I am passing with return array.
This is the code in CONTROLLER file:-
namespace Drupal\custom_module\Plugin\Block;
use Drupal\Core\Block\BlockBase;
class HeaderBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$data['test_var'] = '1234';
return array(
'#type' => 'markup',
'#theme' => 'block--header_block',
'#desc' => 'Description here',
'#data' => $data
);
}
}
I'm not able to display the value of {{ desc }} or {{ data.test_var }} variables in custom block twig template.
I have also added below code in hook_theme() in custom module file.
MODULE_FILE:-
function mytheme_theme($existing, $type, $theme, $path) {
return array(
'block__header_block' => array(
'render element' => 'elements',
'template' => 'block--header_block',
'base hook' => 'block',
'variables' => array(
'data' => NULL
)
)
);
}
Please let me know if anyone has this issue and resolved it.
Thanks
Comments
Comment #3
ao2 CreditAttribution: ao2 as a volunteer commentedI was in a similar situation.
One thing I noticed in the posted code is that in
HeaderBlock::build()
, at the line'#theme' => 'block--header_block',
, the value contains hyphens instead of underscores.However, even fixing that might not be enough.
I has some more luck by dropping the
block__
andblock--
prefixes everywhere (in the example above: inhook_theme()
, inHeaderBlock::build()
, and in the template file name.After that the variables were picked up, but I was getting a message like this:
That went away by removing these lines from
hook_theme()
:In particular the second one was triggering the message above.
BTW I think the
'template'
line could be dropped too.I am new to this part of Drupal, so I'd like confirmation that my indications make sense.
Thanks,
Antonio
Comment #7
ivnish CreditAttribution: ivnish commented