4

I am trying to modify the meta tags of one of the pages of my web. For example, I want to change the title, the description and add the robots tag.

I have tried using the token and metatag modules to change this, but it is too generic and I do not see the option to change it individually on each page.

Also keep in mind that the page on which I want to change these tags is generated by a custom module: creating the Twig manually and generating the URL by routing.yml. There's the problem, that by not generating by the back, it does not recognize it as a page.

1

3 Answers 3

5

Inside module_name.module:

/**
 * Implements hook_page_attachments().
 */
function module_name_page_attachments(array &$page) {
  $description = [
    '#tag' => 'meta',
    '#attributes' => [
      'name' => 'description',
      'content' => 'This is content.',
    ],
  ];
  $page['#attached']['html_head'][] = [$description, 'description'];
}
2

I've tested successfuly Metatag Routes module for Drupal 8. The module adds a button in the default metatag dashboard page. The user can configure metatags for custom controllers generated by code.

enter image description here

To complete the solution where we use a hook. We can add a condition to apply the meta description to a specific route:

/**
 * Implements hook_page_attachments().
 */
function module_name_page_attachments(array &$page) {
  // Check if the current route matches the desired route.
  $current_route_name = \Drupal::routeMatch()->getRouteName();

  if ($current_route_name == 'name_of_the_desired_route') {
    $description = [
      '#tag' => 'meta',
      '#attributes' => [
        'name' => 'description',
        'content' => 'This is the description of the desired route.',
      ],
    ];
    $page['#attached']['html_head'][] = [$description, 'description'];
  }
}
0

Metatag_routes does not work if your path has parameters. For example, in my case:

avt_general.page_resources:
  path: '/group/{groupid}/recursos'
  defaults:
  ...

When you add new metatags for "/gruoup/something/recursos" the module associates the data with "avt_general.page_resources", so you cannot add more metatags to "/gruoup/something2/recursos". Hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.