Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

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

Comments

Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts

Search

Page Facebook