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.
By ilclaudio on
Hi all,
I'have a custom block that uses this template: block--mycontenttypeblock.html.twig that is shown only when the node is of type "Mycontenttype".
Is it possible to get the id of the shown node from the block?
So that I can add in this block these urls:
- http://mysite/node/7/edit
- http://mysite/addNote?id=7
-....
Where 7 is the id of the node.
I'm using Drupal8.
Thank you very much.
claudio
Comments
-------
If you have a custom block (extended BlockBase) then in "build" function do this:
$node = \Drupal::routeMatch()->getParameter('node');
You can create there URL to that node, then return that data in an array.
I have a custom block defined
I have a custom block defined in the UI, so I don't have a class related to this block.
I don't know if I can associate a custom class to my custom block and eventually I don't know where to define this class.
I've used the preprocess hook
I don't know if it is the best solution, but I've solved in this way:
1) I've added in the file "mytheme.theme" the hook "mytheme_preprocess_block":
/**
* Implements hook_preprocess_HOOK() for block.html.twig.
*/
function mytheme_preprocess_block(&$variables) {
$node = \Drupal::routeMatch()->getParameter('node');
if ($node) {
$nid = $node->id();
} else {
$nid = 0;
}
$variables['nodeid'] = $nid;
}
2) In the file block--mycontenttypeblock.html.twig I've used the new variable:
{{nodeid}
And now the block prints the node id in the right way.
cld