Sven Decabooter: How to add classes / attributes to Drupal 8 local tasks

0 Flares Twitter 0 Facebook 0 Filament.io 0 Flares ×
How to add classes / attributes to Drupal 8 local tasks

Drupal 8 allows you to define custom tabs (a.k.a. local tasks) in your custom module.
For theming purposes, it might be necessary to add a class, ID, or other HTML attribute to the tab link.

Here is how this can be achieved when defining the local task in your [modulename].links.task.yml:

entity.node.custom:
  route_name: entity.node.custom
  base_route: entity.node.canonical
  title: 'Custom local task / tab'
  options:
    attributes:
      class:
        - 'my-custom-class'

If you want to add an attribute to a local task that is not defined in your custom module, you could use a preprocess function in your theme or module:

/**
 * Implements hook_preprocess_menu_local_task().
 */
function MYTHEME_preprocess_menu_local_task(&$variables) {
  /** @var DrupalCoreUrl $url */
  $url = $variables['link']['#url'];
  if ($url instanceof DrupalCoreUrl && $url->getRouteName() == 'entity.node.custom') {
    $variables['link']['#options']['attributes']['class'][] = 'my-custom-class';
  }
}

Replace the route name in the example above, with the route name of the tab you wish to change the HTML attributes for.

Sven Decabooter
Mon, 04/15/2019 – 11:17