3

I want to make a module which will add some attributes in an anchor tag, whether the user adds in CKEditor or it is from Drupal menu system, before rendering it to the browser.

I can do it through jQuery with $('a').attr('data-anchor', 'arial');, but is there any way to do it through a module?

  • I think you mean through PHP? Because you can add your jQuery to your module and make file.js load on every page or on specific pages. – No Sssweat Jan 22 '17 at 8:46
  • Yes, I want to do through PHP because jQuery may increase the rendering time. – Akash Jain Jan 22 '17 at 8:50
3

You can do it using hook_link_alter

/**
 * Implements hook_link_alter().
 */
function mymodule_link_alter(&$variables) {

    $variables['options']['attributes'] = array('data-anchor' => 'arial');

}
  • Thanks for your answer but I think this might not work in my case. I want to alter all anchor tag whether the user added through CKEditor or rendering through a block like <a href="example.com">Hello<./a>. I don't think this hook will call for anchor tag that defined in content. – Akash Jain Jan 22 '17 at 9:26
  • After testing, yes that's correct, this does not work with CKEditor. I would stick to the jQuery method, a few lines of jQuery will not slow you down. – No Sssweat Jan 22 '17 at 9:41
  • 2
    @AkashJain, that's a different question. You need a text filter. See drupal.org/docs/8/api/filter-api/overview. The last link on this page has a good tutorial. – 4k4 Jan 22 '17 at 9:46
  • @4k4 is correct, even if you manually type in CKEditor <a href="/node/1" data-anchor="arial">link</a> the data-anchor="arial" part gets filtered out, removed. So I guess you need to create a text filter so it allows it. – No Sssweat Jan 22 '17 at 10:06
  • 2
    Yes, if you want to add attributes in a text filter you can use the DOM structure of the field content, see drupal.stackexchange.com/questions/208445/… – 4k4 Jan 22 '17 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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