0

Is it possible to get the absolute path to the homepage or <front> eg: https://www.domain.com/homepage in the theme_preprocess_html hook? I tried global $base_url but it throws an error.

  • 2
    Possible duplicate of How to get the base URL of a site – leymannx Jan 2 at 18:37
  • global $base_url; – leymannx Jan 2 at 18:38
  • Hello again @leymannx :) global $base_url throws an error. I got the absolute path with this though: \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]); which is in the duplicate question you posted but hidden in one of the comments. – Kris Robinson Jan 2 at 18:48
  • Hey hey, what error? – leymannx Jan 2 at 20:42
  • Error: ParseError: syntax error, unexpected 'global' (T_GLOBAL) in Drupal\Core\Extension\Extension->load() – Kris Robinson Jan 3 at 21:20
1

I used \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]); from one of the comments in:

How to get the base URL of a site

Here is the entire working snippet:

/**
 * Implements hook_preprocess_html().
 */
function mytheme_preprocess_html(&$variables) {

  // Modify if we're on nodes
  if ($node = \Drupal::request()->attributes->get('node')) {
    // Get the node-type
    $nodetype = $node->getType();
    // Switch class for node-type
    switch ($nodetype) {
      case "landing":
        // prefetch frontpage from landing pages
        $frontpage_path = \Drupal::urlGenerator()->generateFromRoute('<front>', [], ['absolute' => TRUE]);
        $prefetchfront = [
          '#tag' => 'link',
          '#attributes' => [
            'rel' => 'prefetch prerender',
            'href' => $frontpage_path,
          ],
        ];
        $variables['page']['#attached']['html_head'][] = [$prefetchfront, 'prefetch'];
      break;
    }
  }
}
  • 1
    You shouldn't generate the url at this point, only create a url data object and let the render engine do the rest: Url::fromRoute('<'front'>', [], ['absolute' => TRUE]) – 4k4 Jan 3 at 9:22
  • Gives error: ParseError: syntax error, unexpected 'front' (T_STRING), expecting ',' or ')' in Drupal\Core\Extension\Extension->load() – Kris Robinson Jan 3 at 21:19
  • It probably should be '<front>' in @4k4's comment. – leymannx Jan 3 at 21:25
  • 1
    Yes, @leymannx, the route name has a typo. The point is to use \Drupal\Core\Url::fromRoute() instead of UrlGeneratorInterface::generateFromRoute, which is marked as internal and shouldn't be used in user code. – 4k4 Jan 3 at 21:38
  • 1
    @KrisRobinson, now after seeing the code snippet I would suggest: Url::fromRoute('<front>')->setAbsolute()->toString() – 4k4 Jan 4 at 10:46

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.