0

We are attempting to change the $variables['url'] from a relative to absolute URL within the mymodule_preprocess_node() hook. The $variables['url'] is displayed as a <a> element within our node--page.html.twig template.

How can we set the $variable['url'] so that it uses the absolute URL?

node--page.html.twig

<a href="{{ url }}">
  {{ label }}
  {{ content.field_text }} {# custom text field #}
</a>

What we tried within mymodule_preprocess_node().

use Drupal\Core\Url; 

function mymodule_preprocess_node($variables) {
  $options = [
    'absolute' => true,
  ];
  $variables['url'] = URL::fromUri($variables['url'], $options);
}

This results in the following error message:

The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core\lib\Drupal\Core\Url.php).

1

In order to get this to work, I did the following. This assume you have access to the $node object, which you would if you are performing this within the hook_preprocess_node() hook.

$variables['url'] = $node->toUrl()->setAbsolute()->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.