We are using Drupal Core v8.6.2 and we have a url variable in our node--page.html.twig template. While using ksm() and {{ kint() }} we are finding that if we use hook_preproces_node($variables) that the url is inserted into the $variables array. Unfortunately this url is relative, but we need an absolute URL in our twig template.

How can we convert this url variable from our node--page.html.twig template to be absolute?


I have reduced the comments section to only include comments that were relevant to the question.

 * @file
 * Theme override to display a node.
 * Available variables:
 * - node: The node entity with limited access to object properties and methods.
 * - label: The title of the node.
 * - content: All node items. Use {{ content }} to print them all,
 * - url: Direct URL of the current node.
 * - attributes: HTML attributes for the containing element.
 * @see template_preprocess_node()

<a href="{{ url }}> {# url is the variable we want to be absolute #}
  <h2> {{ label }} </h2>
  {{ content.body }}
  • How are you creating this variable? – Kevin Dec 31 '18 at 18:28
  • @Kevin I added more lines from the comment's section of the twig template in the question. It is a copy of the node.html.twig from the classy node.html.twig template. So nothing I generated myself. – usernameabc Dec 31 '18 at 18:42

You can use hook_preprocess_node to passe base_url to your twig like the following:

function mymodule_preprocess_node(&$variables) {
  global $base_url;
  $variables['base_url'] = $base_url;

in node--page.html.twig you will get the absolute url by:

{{ base_url ~ url }} 
|improve this answer|||||

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.