I am trying to render a block depending on the parameter(entity) present in the requested page. Suppose if I am on a url like this: http://localhost/drupal8/user/1 then a block with label user is created. Same thing I am trying to achieve for other urls like http://localhost/drupal8/node/1, http://localhost/drupal8/comment/1. I am using this piece of code:

if ($this->request->attributes->has($entity_type)) { return code for rendering block }

(here $entity_type will be replaced by user,comment,node) to check whether requested page has a particular key. This piece of code works for checking keys like node and user when I am on page http://localhost/drupal8/node/1 and http://localhost/drupal8/user/1 respectively but when I am on page like http://localhost/drupal8/comment/1 and check for key: 'comment' then it returns FALSE because it is not defined. Is this an expected behaviour, if yes then what should I do to solve my problem. Thanks.

  • You can have a look at array_keys($this->request->attributes->all()) to see what kind of entries exists Jun 14, 2015 at 19:45
  • @DanielWehner , I have already done that to know whether comment exists as a key. It doesn't exist as key hence I am not able to get an instance of comment entity (by using $this->request->attributes->all()) which I need to render block content. I hope u have understood my problem. Jun 14, 2015 at 20:49
  • sorry mistyped in above comment above: (by using $this->request->attributes->get()). Jun 14, 2015 at 21:00

1 Answer 1


Instead of inspecting the request object directly, the current_route_match service is the preferred object to consult for request parameters. It provides both the raw and upcast values of parameters. Additionally, using \Drupal\Core\Routing\StackedRouteMatchInterface you can retrieve values from the master request.

The reason you are having trouble with /comment/{comment} is because that route is special: it performs a subrequest to view the entity the comment belongs to. This explains why you only have the node entity available when viewing a comment on a node.

To work around this, consult the master request:

$comment = \Drupal::routeMatch()->getMasterRouteMatch()->getParameter('comment');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.