Score:1

Adding a class to a URL object

um flag
function mytheme_preprocess_menu_local_tasks(&$variables) {
  if (!empty($variables["primary"]["entity.node.edit_form"]["#link"]["url"])) {
    $url = $variables["primary"]["entity.node.edit_form"]["#link"]["url"];
    assert($url instanceof Url);
    $nid = $url->getRouteParameters()['node'];
    $node = Node::load($nid);
    if (_mytheme_some_condition($node)) {
      $attributes = (array) $url->getOption('attributes');
      $attributes['class'][] = 'little-red-riding-hood';
      $url->setOption('attributes', $attributes);
    }
  }
}

That's just awful. Surely there's a better way to do this?

Score:2
cn flag

Add the class to

...['#link']['localized_options']['attributes']['class'][] = 'foo';

The Link and Url options are merged in the Link render element.

Smartsheet eng avatar
um flag
`template_preprocess_menu_local_task` and `template_preprocess_menu_local_action` copies `localized_options` into `#options` for the `Link` Render element and that is indeed merged in there like this: `$options = NestedArray::mergeDeep($element['#url']->getOptions(), $element['#options']);` I saw the empty `localized_options` array in the debugger but I had no idea what it did and it's completely undocumented as far as I can see. Thanks! So this solution only works for these two kind of links, normal `'#type' => 'link'` render arrays should use `#options`.
4uk4 avatar
cn flag
Yes, `'#type' => 'link'` is the render element I've mentioned.
Score:0
ua flag

Not sure if you like this more. Alternatively, you could add a menu-local-task.html.twig and do something like

{% if condition %}
  <li{{ attributes.addClass('little-red-riding-hood' }}>{{ link }}</li>
{% else %}
  <li{{ attributes }}>{{ link }}</li>
{% endif %}
Smartsheet eng avatar
um flag
That puts the class on `<li>` not the `<a>`.
No Sssweat avatar
ua flag
@̷c̷h̷x̷ You could still target with `.little-red-riding-hood a`. Though if you need to load the Node object for your check, might as well stick with your preprocess approach I guess.
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.