3

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.

Thanks.

2 Answers 2

7

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();
0
0

Digging it up to provide a broader approach. As per the documentation, one can use the "fragment" option in order to attach an anchor (#) to a drupal Link.

e.g.

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

$url = Url::fromRoute('example.route', ['route_parameter' => 'example'], ['fragment' => 'anchor-section']);
$link = Link::fromTextAndUrl(t('Link with anchor'), $url);

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.