Drupal - Is there a way to tell if the current page is a node?

\Drupal::request()->attributes->get('node');

Taken from here: https://api.drupal.org/api/drupal/core!lib!Drupal.php/function/Drupal%3A%3Arequest/8

Now the docs say to never use this function, but I have used this to determine what kind of page I am on.

There is another function, but I am not sure it applies in your case:

https://api.drupal.org/api/drupal/core%21modules%21node%21node.module/function/node_is_page/8

At the very least, if you do not have an entity, you could mimic that in your code:

  $route_match = \Drupal::routeMatch();

  if ($route_match->getRouteName() == 'entity.node.canonical') {
    return true;
  }

In your own module I think the recommended way is

$node = \Drupal::routeMatch()->getParameter('node');
if ($node instanceof \Drupal\node\NodeInterface) {
  // It's a node!
}

In the page template a variable for the node is already available, which you can use in twig.

To tell, if the current page is a node, you can check, if node exists:

page.html.twig

{% if node %}
  <h1>This is a node</h1>
{% endif %}

This is possible, because this code is in core:

core/includes/theme.inc:
function template_preprocess_page(&$variables) {
  ...
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $variables['node'] = $node;
  }
}

This will work on /node/[id] and url aliases.

Tags:

Nodes

8