0

I want to programmatically decide whether to render a link or not. This should apply to all links e.g anchor tags (no wysywigs) Not only menu links.

I tried using hook_link_alter.

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {
  $my_logic = TRUE;
  if ($my_logic) {
    // Any way to not render the link?
    // I tried:
    // $variables = []; and unsetting keys with no luck
    // $variables['options']['#access'] = FALSE; With no luck.
    // I guess i could set a flag here and somewhere else process it, but where?
  }
}

I can alter the structure, but I don't see any way to unset the element. What I want is basically to not render the element if $my_logic.

I also tried to use a service with the path_processor_outbound tag, but I have the same problem. I can "access" all generated links but can just alter / modify the output of processOutbound() but not to not process.

I think I can´t use a custom access check because i don´t want the url´s to be inaccessible if directly requested and I rather don´t want to do the check in a template

2
  • 2
    Unsetting a link wont make the path inaccessible FYI - you need permissions or access control for that.
    – Kevin
    Commented May 9, 2022 at 12:58
  • @Kevin Thx for pointing that out, actually custom-access might be a way to go, it´s not a requirement to be inaccessible, i just dont want to render the path and it´s link element into the source
    – john Smith
    Commented May 9, 2022 at 13:06

1 Answer 1

0

I couldn't find a way to prevent the link from rendering, but I did find a couple of ways of hiding it, which was good enough in my use case.

  • Add a 'hidden' class to the link (along with CSS to display:none it)
  • Set the link text to an empty string.
  $item['options']['attributes']['class'][] = 'hidden';
  $item['text'] = "";

If your goal is just to tidy up a menu/hide a link rather than prevent access to the destination page then this might help.

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.