7

I am trying to make a link pointing to # but am unable to find a method that works.

The output i would like to see is

<a href="#">Example</a>

I have tried a few variations of the following without success.

$url = Url::fromUserInput('#');
$link_item = Link::fromTextAndUrl(t('Example'), $url);
return $link_item->toRenderable();

I have also tried using ::fromUri etc and am unable to find a method that produces tehd esired output, please help.

2

2 Answers 2

8

It's probably not possible to attach an empty fragment. See this code in UrlGenerator::generateFromRoute():

if (isset($options['fragment'])) {
  if (($fragment = trim($options['fragment'])) != '') {
    $fragment = '#' . $fragment;
  }
}

If the fragment is empty it is ignored and no '#' shows up. This doesn't change if you provide the fragment in Url::fromUserInput(), because the fragment is transfered to the options and later processed by the same or similar code.

So you have to provide an anchor in the fragment:

$url = Url::fromUserInput('#anchor1');

or

$url = Url::fromRoute('<current>', [], ['fragment' => 'anchor2']);

As alternative option you can place a link with an empty fragment

<a href="#">{{ examplevariable }}</a>

either in a twig template or in an inline template in php.

0

The following code:

$link = \Drupal\Core\Link::fromTextAndUrl(
          t('Example'),
          \Drupal\Core\Url::fromUserInput('#', ['fragment' => '#'])
        )->toString();`

will return:

<a href="##">Example</a>


Here is the example to return a custom path:

\Drupal\Core\Link::fromTextAndUrl(t('Example'), \Drupal\Core\Url::fromUri('base:/some/path'))->toString();

which returns:

<a href="/some/path">Example</a>

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.