6

How do I get the base_path in Drupal 8? When I use the base_path() function it always returns just the /. I know in Drupal 7 you could set the base_url in the settings.php file, but how do I set it in Drupal 8?

I'm trying to create an absolute url for social media sharing.

1 Answer 1

6

You're looking for $base_url global:

global $base_url; 

If you want to have this in a preprocess function, you'd have to call it within that function; for example:

function YOUR_THEME_preprocess_whatever(&$variables) { global $base_url; // Now you can use it. $variables['base_url'] = $base_url; } 
4
  • I tried that, and it too only returns / - what ended up working was calling $GLOBALS['base_url']; Commented Mar 4, 2016 at 7:50
  • That's strange; it shouldn't work that way. I tested it on a couple of D8 sites (live and dev) and it works fine. $GLOBALS['base_url'] is equivalent of the code I wrote above. Commented Mar 4, 2016 at 8:05
  • I also thought it should do the same thing. What I did is add global $base_url to the top of my themename.theme file and then in one of my preprocess functions I tried accessing $base_url, and I get an error 'Undefined variable: base_url' ? am i doing something wrong there? Commented Mar 4, 2016 at 8:10
  • Yes :) you need to add it within your preprocess function. I'll update the answer. Commented Mar 4, 2016 at 8:11

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.