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

PrzemyslawKot’s picture

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.

ilclaudio’s picture

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.

ilclaudio’s picture

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