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
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.
- 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 usesDrupal::routeMatch()
to get the current route match object, thengetRouteName()
to get the current route name. - 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 replacedesired_route_name
with the name of the road you want to target. If the condition istrue (that is, the current route matches the desired route), we run the code inside that condition.
- 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. - 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.
Add new comment