In this tuto, I'll show you how to get the route name of the current page in Drupal 8.
To get the current route name, use:
$route_name = \Drupal::routeMatch()->getRouteName();
or
$current_route_name = \Drupal::service('current_route_match')->getRouteName();
To check if the current page is a taxonomy term use:
if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical') {
$term_id = \Drupal::routeMatch()->getRawParameter('taxonomy_term');
}
To check if the current page is a node, node preview or node revision use:
$route_match = \Drupal::routeMatch();
if ($route_match->getRouteName() == 'entity.node.canonical') {
$node = $route_match->getParameter('node');
}
elseif ($route_match->getRouteName() == 'entity.node.revision') {
$revision_id = $route_match->getParameter('node_revision');
$node = node_revision_load($revision_id);
}
elseif ($route_match->getRouteName() == 'entity.node.preview') {
$node = $route_match->getParameter('node_preview');
}
To check if the current page is a contact form page use:
if (\Drupal::routeMatch()->getRouteName() == 'entity.contact_form.canonical') {
// contact form
$contact_form = \Drupal::routeMatch()->getParameter('contact_form');
}
To check if the current page is a view page use:
$current_route_name = \Drupal::service('current_route_match')->getRouteName();
The route names from views are built like this view.[view_name].[display_id].
List the existing routes:
You can list the existing routes with Drupal Console:
drupal router:debug