6

I've used custom templates to add BEM style classes to both the local tasks UL wrapper and the individual LI items, I'd like to also add a class to the actual local task (tab) link.

This is the default code in the Classy template:

<li{{ attributes.addClass(is_active ? 'is-active') }}>{{ link }}</li>

Is there no way to simply add a class to the {{ link }} item?

3 Answers 3

13
{% set link = link|merge({ '#attributes': { 'class': [ 'your', 'custom', 'classes' ] } }) %}

<li>{{ link }}</li>
2
  • 1
    Please don't post code-only answers. Try to explain what the code does and why it solves OP's problem.
    – Shawn Conn
    Jun 10, 2016 at 19:39
  • 3
    It's the solution and self explanatory. Clean and clear way. Jan 25, 2019 at 13:43
4

you can add a class with the attribute array of the TWIG function :

{{ link(item.title, item.url, { 'class':['my-custom-class'] }) }}

unfortunately, this overrides any classes added preprocessing by other contrib modules. Im currently looking for a way to append new class to the {{ link }}

2

You can't from the template, but you can do it from a preprocess hook. If you look at the original from Drupal:

function template_preprocess_menu_local_task(&$variables) {
  ...
  $variables['link'] = array(
    '#type' => 'link',
    '#title' => $link_text,
    '#url' => $link['url'],
    '#options' => $link['localized_options'],
  );
}

In a theme, you could add a class in your own preprocess, something like this should do the trick:

function THEME_preprocess_menu_local_task(&$variables) {
  $variables['link']['#options']['attributes']['class'][] = 'my-extra-class';
}

Your Answer

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

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