Skip to main content
Menu
Offcanvas

Ajouter une meta description à une seule route générée par un module Drupal.

If you are creating a route with a Drupal module, you may need to add a meta description to this page. You can use the hook_page_attachments() hook

Add a meta description to a single route generated by a Drupal module.

To limit this meta description to a single route, you need to check which route is currently displayed and act accordingly. You can do this using the information available in Drupal's Request object.

Here's how you can add the meta description only to a specific route:

Code

/**
 * Implements hook_page_attachments().
 */
function module_name_page_attachments(array &$page) {
  // Vérifiez si la route actuelle correspond à la route souhaitée.
  $current_route_name = \Drupal::routeMatch()->getRouteName();

  if ($current_route_name == 'nom_de_la_route_souhaitee') {
    $description = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'description',
        'content' => 'Ceci est la description de la route souhaitée.',
      ],
    ];
    $page['#attached']['html_head'][] = [$description, 'description'];
  }
}

 

Explanation of the code

  1. The

    hook_page_attachments()

    hook is a Drupal hook that allows you to add elements to the page being rendered. This includes elements to add in the <head> tag of the page, such as meta tags.

  2. Inside the module_name_page_attachments()function, we start by getting the current route name using$current_route_name = \Drupal::routeMatch()->getRouteName();. This line of code uses Drupal::routeMatch() to get the current route match object, then getRouteName() to get the current route name.
  3. Next, we use a conditional if structure to check if the current route name matches the specific route we want to target. You need to replace desired_route_name with the name of the road you want to target. If the condition is true (that is, the current route matches the desired route), we run the code inside that condition.
  4. Inside the condition, we create a $description array that represents the meta tag we want to add. In this example, the meta tag has a name attribute equal to "description" and a content attribute with the value of the description you want to display.
  5. Finally, we add the meta tag to the $page['#attached']['html_head'] array. This ensures that the meta tag will be added to the <head> section of the generated HTML page. The 'description' key is used to identify this meta tag among other <head> elements, such as <link> tags or other <meta> tags.

Other useful resources

Add new comment

Similar blog posts

How to delete local changes with git that you haven't committed ?

LIRE LA SUITE