In relation to Drupal 8 ... if a user wanted to create a link such as the following:

<a href='#' onClick='testfunction ();'>link</a>

How could such a link be created, normally creating a link requires the use of the Url object and so the symbol '#' can't normally be used, nor can 'javascript:void (0)'.

Essentially I'm trying to create an link with an anchor tag in it.



Url component is not able to generate URLs with empty anchors, so you need create an anchor on your page or use existing one.

use Drupal\Core\Link;
use Drupal\Core\Url;

$url = Url::fromUserInput('#main-content');
print Link::fromTextAndUrl(t('Link text'), $url)->toString();

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.